本文介绍了在 mongodb 中更新子文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

文档:

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

推荐答案

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

By specifying actual position of embedded document like this:

// 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" }} )

这篇关于在 mongodb 中更新子文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 08:40