2012-02-22 76 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