Replacing embedded document in array in MongoDB

被刻印的时光 ゝ 提交于 2019-12-18 13:07:52

问题


Is there an easy way to replace an entire embedded document in an array? Say replacing:

{
   "_id" : "2",
      "name" : "name2",
      "xyz..." : "xyz2..."
}

with:

{
   "_id" : "2",
      "name" : "name6",
      "xyz..." : "xyz5..."
      "morefields..." : "fields..."
}

Searching for _id (embedded). Or do I need to replace each field individually using $set?

{
  "_id" : "2",
  "users" : [{
      "_id" : "1",
      "name" : "name1",
      "xyz..." : "xyz1..."
    }, {
      "_id" : "2",
      "name" : "name2",
      "xyz..." : "xyz2..."
    }],
  "name" : "main name"
}

回答1:


You are using the "array of objects" pattern. You can use the positional operator, it should look something like this:

coll.update( {'_id':'2', 'users._id':'2'}, {$set:{'users.$':{ "_id":2,"name":"name6",... }}}, false, true)

In my experience, the "array of objects" pattern is not optimal if the objects have a natural ID. In your case, this could be modeled as the following:

{
  "_id" : "2",
  "users" : 
    { "1" : { "name" : "name1", "xyz..." : "xyz1..." }, 
      "2" : { "name" : "name2", "xyz..." : "xyz2..." }
    }
  "name" : "main name"
}

In this case you can use the dot notation to easily update the item you want.

var newValue = {  "name" : "name6", "xyz..." : "xyz5...", "morefields..." : "fields..." };
coll.update({_id: 2}, { $set: { "users.2" : newValue } });


来源:https://stackoverflow.com/questions/9200399/replacing-embedded-document-in-array-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!