在mongodb中更新子文档?

Ind*_*ial 24 mongodb

如何定位authors数组中的子文档,如下所示,以便更新它?

collection.update({'_id': "4f44af6a024342300e000001"}, {$set: { 'authors.?' }} )
Run Code Online (Sandbox Code Playgroud)

文件:

{
    _id:     "4f44af6a024342300e000001",
    title:   "A book", 
    created: "2012-02-22T14:12:51.305Z"
    authors: [{"_id":"4f44af6a024342300e000002"}] 
}
Run Code Online (Sandbox Code Playgroud)

And*_*ich 38

通过指定嵌入文档的实际位置,如下所示:

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

或通过位置操作员:

// 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" }} )
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法更新所有嵌套文档文件? (2认同)