【问题标题】:MongoDB Change/Update Subdocument FieldMongoDB 更改/更新子文档字段
【发布时间】:2017-05-28 02:42:57
【问题描述】:

我目前有一个 Mongo DB 数据库,其中包含一个集合(“位置”)和一个文档:

{
"_id" : ObjectId("5875653b89513c8328416522"),
"name" : "Starcups",
"address" : "125 High Street, Reading, RG6 1PS",
"rating" : 3,
"facilities" : [
    "Hot drinks",
    "Food",
    "Premium wifi"
],
"coords" : [
    -0.9690884,
    51.455041
],
"openingTimes" : [
    {
        "days" : "Monday - Friday",
        "opening" : "7:00am",
        "closing" : "7:00pm",
        "closed" : false
    },
    {
        "days" : "Saturday",
        "opening" : "8:00am",
        "closing" : "5:00pm",
        "closed" : false
    },
    {
        "days" : "Sunday",
        "closed" : true
    }
],
"reviews" : [
    {
        "author" : "Simon Holmes",
        "id" : ObjectId("5875663389513c8328416523"),
        "rating" : 5,
        "timestamp" : ISODate("2013-07-15T23:00:00Z"),
        "reviewText" : "What a great place. I can't say enough good things about it."
    }
]
}

我需要将字段“id”(子文档评论的一部分)更改为“_id”。我已经尝试过,在 StackExchange 上使用其他类似的示例,以下代码无济于事:

db.locations.update({}, {$rename:{"reviews.id":"reviews._id"}}, false, true);

但我收到以下错误:

WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
    "code" : 16837,
    "errmsg" : "cannot use the part (reviews of reviews.id) to traverse the element ({reviews: [ { author: \"Simon Holmes\", id: ObjectId('5875663389513c8328416523'), rating: 5.0, timestamp: new Date(1373929200000), reviewText: \"What a great place. I can't say enough good things about it.\" } ]})"
}
})

当我尝试更改任何其他字段时,我得到了同样的错误。有人能指出我正确的方向吗?

更新:

这似乎是评估子文档字段的问题,因为以下代码执行良好:

db.locations.update({}, {$rename:{"name":"names"}}, false, true);

我也试过搜索相关文档:https://docs.mongodb.com/manual/reference/operator/update/rename/

【问题讨论】:

    标签: json node.js mongodb mongoose database


    【解决方案1】:

    那是因为评论是Array

    您不能 $rename 这样做,而是需要 $set 新名称并 $unset 旧名称

    【讨论】:

    • 谢谢 - 这是因为 [ ] 在评论中包含了不同的值,对吗?另外,当我使用来自其他地方的这些数据时,是否有任何理由为什么在这种情况下,数组比对象更有用?每个“位置”条目可能附有多个评论。会不会是这个原因?
    猜你喜欢
    • 2021-01-28
    • 1970-01-01
    • 2011-08-04
    • 2013-01-06
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多