update array of embedded documents with array of embedded documents

49 views
Skip to first unread message

Martinus Martinus

unread,
Nov 14, 2012, 11:27:33 PM11/14/12
to mongod...@googlegroups.com
Hi,

Is there any mongodb command to do updating an array of embedded documents with array of embedded documents? So supposed I have below existing document :

{
    "_id" : 1,
    "name" : "Bob",
    "year" : 2012,
    "animal_ref" : DBRef("animal", ObjectId("1")),
    "array" : [{
                    "date" : ISODate("2012-11-11T09:00:00Z"),
                    "food" : 10
                  },
                  {
                    "date" : ISODate("2012-11-11T18:00:00Z"),
                    "food" : 10
                  }]
}

And I have a new "array" to be combined with the existing array like below :
    "array" : [{
                    "date" : ISODate("2012-11-11T09:00:00Z"),
                    "food" : 15
                  },
                  {
                    "date" : ISODate("2012-11-11T19:00:00Z"),
                    "food" : 20
                  }]

And the result of this combining process will become like below :
{
    "_id" : 1,
    "name" : "Bob",
    "year" : 2012,
    "animal_ref" : DBRef("animal", ObjectId("1")),
    "array" : [{
                    "date" : ISODate("2012-11-11T09:00:00Z"),
                    "food" : 15
                  },
                  {
                    "date" : ISODate("2012-11-11T18:00:00Z"),
                    "food" : 10
                  },
                  {
                    "date" : ISODate("2012-11-11T19:00:00Z"),
                    "food" : 20
                  }]
}

Thanks.
               

Asya Kamsky

unread,
Dec 11, 2012, 10:48:19 PM12/11/12
to mongod...@googlegroups.com
Martinus,

There is a way to do this, it's described in the manual here:  http://docs.mongodb.org/manual/reference/operators/#_S_each

What you want to use is an update with "$addToSet" operator and "$each" operator to specify the new array and have only non-duplicates added to existing array.

For you that would be:  db.collection.update(  { <query>} ,  { $addToSet : { array : { $each : [ <new array you want to merge ] } } } )

Asya

Martinus Martinus

unread,
Jan 10, 2013, 10:02:41 PM1/10/13
to mongod...@googlegroups.com
Hi Asya,

Thanks for your answer. It's worked.

Thanks again and Happy New Year 2013.

Best regards,

Martinus

--
You received this message because you are subscribed to the Google
Groups "mongodb-user" group.
To post to this group, send email to mongod...@googlegroups.com
To unsubscribe from this group, send email to
mongodb-user...@googlegroups.com
See also the IRC channel -- freenode.net#mongodb

Reply all
Reply to author
Forward
0 new messages