Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing embedded document in array in MongoDB

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"
}
like image 684
Fredrik L Avatar asked Feb 08 '12 19:02

Fredrik L


People also ask

How do I update an embedded array in MongoDB?

To perform an update on all embedded array elements of each document that matches your query, use the filtered positional operator $[<identifier>] . The filtered positional operator $[<identifier>] specifies the matching array elements in the update document.

How do I remove an element from an array in MongoDB?

To remove an element, update, and use $pull in MongoDB. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

How do I access an embedded document in MongoDB?

Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.


1 Answers

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 } });
like image 111
Gates VP Avatar answered Sep 21 '22 04:09

Gates VP