user2629996
user2629996

Reputation: 35

Adding subdocuments in a document

I would like to add multiple subdocuments in a document.

What would be correct way of adding them?

db.document.update({'_id':99999},{$set:{'student':{'name':'Jack','marks':90}}})  
db.document.update({'_id':99999},{$set:{'student':{'name':'Jill','marks':75}}})

Above statement inserts last subdocument in the document.

Using array update operators is giving error.

Sorry, if this is re-post. Could not find answer anywhere.

Upvotes: 0

Views: 89

Answers (1)

Leonid Beschastny
Leonid Beschastny

Reputation: 51480

Array operations work fine:

db.document.insert({'_id':99999})
db.document.update({'_id':99999},{$push:{'student':{'name':'Jack','marks':90}}})  
db.document.update({'_id':99999},{$push:{'student':{'name':'Jill','marks':75}}})

Now

db.document.findOne({_id: 99999})

will give you

{
  "_id" : 99999,
  "student" : [
    {
      "name" : "Jack",
      "marks" : 90
    },
    {
      "name" : "Jill",
      "marks" : 75
    }
  ]
}

Error on $push means that you already have that field in your document and it's not an array.

For example, the following code will give you an error on $push

db.document.insert({'_id':99998,'student':{'name':'Jack','marks':90}})
db.document.update({'_id':99998},{$push:{'student':{'name':'Jill','marks':75}}})

and the following code will not

db.document.insert({'_id':99997,'student':[{'name':'Jack','marks':90}]})
db.document.update({'_id':99997},{$push:{'student':{'name':'Jill','marks':75}}})

Upvotes: 4

Related Questions