简体   繁体   English

MongoDB更改/更新子文档字段

[英]MongoDB Change/Update Subdocument Field

I currently have a Mongo DB database with one collection ('locations') with one document: 我目前有一个Mongo数据库数据库,其中包含一个文档集合('locations'):

{
"_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."
    }
]
}

I need to alter the field "id" (part of the subdocument reviews) to "_id". 我需要将字段“id”(子文档审阅的一部分)更改为“_id”。 I have tried, using other similar examples on StackExchange, the following code to no avail: 我尝试过,使用StackExchange上的其他类似示例,以下代码无济于事:

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

But I receive the following error: 但是我收到以下错误:

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.\" } ]})"
}
})

I get the same error when I try to alter any other field. 当我尝试改变任何其他字段时,我得到相同的错误。 Could someone point me in the right direction? 有人能指出我正确的方向吗?

Update: 更新:

This seems to be a problem assessing the subdocument field as the following code executes fine: 这似乎是评估子文档字段的问题,因为以下代码执行正常:

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

I have also tried searching through the relevant documentation: https://docs.mongodb.com/manual/reference/operator/update/rename/ 我也尝试搜索相关文档: https//docs.mongodb.com/manual/reference/operator/update/rename/

That's because Reviews is an Array 那是因为评论是一个Array

You cannot $rename to do that , instead you need to $set the new name and $unset the old one 您无法$rename来执行此操作,而是需要$设置新名称并取消设置旧名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM