Wikipedia

Search results

20 May 2014

Arrays and nesting in MongoDB

Often, I may have some array that I'd like to access, and here is a demonstration how it can be accomplished with a non-nested and nested array with MongoDB.

For our example using a non-nested array, we have the following instance added to our database and collection

db.foo.insert({_id:'aa', {value:['1', '2']})

To add an item to the list 'value' we'll simply push to array as so

db.foo.update({_id:'aa'}, {$push:{value:'3'}})

The effect of our query for item with '_id' value of 'aa' will be

> db.baz.findOne({_id:'aa'})
{ "_id" : "aa", "value" : [ "1", "2", "3" ] }




Now for the instance with a nested array

db.baz.insert({_id:'bb', {card:{heart:['spade', 'queen', 'jack']}})

We then access the array utilizing dot notation that requires the use of apostrophe like the following

db.baz.update({_id:'bb'}, {$push:{'card.heart':'rook'}})

The effect of the following is to have added an item to the nested array, ending like so

> db.baz.findOne({_id:'bb'})
{
 "_id" : "bb",
 "card" : {
  "heart" : [
   "spade",
   "queen",
   "jack",
   "rook"
  ]
 }
}

No comments:

Post a Comment