2012-02-22 159 views
24

如何为authors阵列定位子文档,如下所示,以便更新它?更新mongodb中的子文档?

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

文件:

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

回答

37

通过指定这样的嵌入文档的实际位置:

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

或通过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" }}) 
+2

有一种方法来更新所有嵌套的文档文件? – BlaShadow 2014-05-01 01:49:59

+0

只需要注意,如果要更新集合中第一个匹配的文档,请确保将{multi:true}作为第三个参数添加到collection.update – dev 2014-07-29 16:16:32

+0

如果它不退出,是否会插入新的子文档? – Pila 2016-09-14 17:39:42