Updating a sub-document in mongodb?

拥有回忆 提交于 2021-02-05 20:21:37

问题


How do I target an subdocument in the authors array as shown below, in order to update it?

collection.update({'_id': "4f44af6a024342300e000001"}, {$set: { 'authors.?' }} )

The document:

{
    _id:     "4f44af6a024342300e000001",
    title:   "A book", 
    created: "2012-02-22T14:12:51.305Z"
    authors: [{"_id":"4f44af6a024342300e000002"}] 
}

回答1:


By specifying actual position of embedded document like this:

// update _id field of first author    
collection.update({'_id': "4f44af6a024342300e000001"}, 
                  {$set: { 'authors.0._id': "1" }} )

Or via positional operator:

// update _id field of first matched by _id author    
collection.update({'_id': "4f44af6a024342300e000001",
                    //you should specify query for embedded document
                    'authors._id' : "4f44af6a024342300e000002" }, 
     // you can update only one nested document matched by query                   
                    {$set: { 'authors.$._id': "1" }} )


来源:https://stackoverflow.com/questions/9401668/updating-a-sub-document-in-mongodb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!