swizzard
swizzard

Reputation: 1095

mongodb update/append-to nested document

Let's say I have a document like this:

{"bar": "blah", 
 "baz": "boo", 
 "quuz": [{"boo": "hi"},   
          {"boo": "lah"}]}

Let's say I've got new data that looks like this:

{"bar": "blah",
 "baz": "boo",
 "quuz": [{"boo": "whatever"},
          {"boo": "etc"}]}

I want to update the document in the db so that it looks like

{"bar": "blah",
 "baz": "boo",
 "quuz": [{"boo": "hi"},   
          {"boo": "lah"},
          {"boo": "whatever"},
          {"boo": "etc"}]}

Can I do this within Mongodb, or should I just pull down the doc, merge it in my app, and then use $set or whatever?

FWIW: I'm using Clojure + Monger.

Upvotes: 0

Views: 204

Answers (2)

Barış Uşaklı
Barış Uşaklı

Reputation: 13522

Should be possible with $push and $each

db.yourCollection.update({
    bar: "blah", 
    baz: "boo"
}, {
    $push: {
        quuz : {$each: [{"boo": "whatever"}, {"boo": "etc"}]}
    }
});

Upvotes: 1

x6iae
x6iae

Reputation: 4164

yes you can do it in mongodb directly.

  1. find the intended object by the common field - in your case, it could either be "bar", or "baz".
  2. isolate property to be updated - "quuz"(an array).
  3. push new data into the array.
  4. save back to database

hope this helps

Upvotes: 0

Related Questions