Replacing embedded document in array in MongoDB

后端 未结 1 1467
后悔当初
后悔当初 2020-12-09 10:45

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

{
   \"_id\" : \"2\",
      \"name\" : \"name2\",
      \"xyz...\" :         


        
相关标签:
1条回答
  • 2020-12-09 11:22

    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 } });
    
    0 讨论(0)
提交回复
热议问题