在mongodb中更新一个子文档?

25

如何定位下面所示的authors数组中的子文档以进行更新?

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

这个文档:

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

39

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

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

或使用位置操作符

// 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
请注意,如果您想要更新集合中的多个匹配文档,确保在collection.update的第三个参数中添加{multi : true}。 - dev
如果没有存在,这会插入一个新的子文档吗? - Pila

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接