I have a document in MongoDB which holds some meta info like the date updated and the _id, and an array of addresses.
{
"_id": {
"$oid": "4e73a30466ca1a1f56000001"
},
"updated": 1316215062,
"address": [
{
"street": "Rotenturmstrasse 8",
"postcode": "1020",
"phone": "Vienna",
"altitude": -1,
"geolocation": [
"11.367464",
"47.204876"
]
}
]
}
Now there could be multiple addresses. I am creating an object for an address which needs to be updated and saving it to the database. This is what the new object to be inserted looks like:
new_object = {
:_id=>BSON::ObjectId('4e73a30466ca1a1f56000001'),
:updated=>1316215099,
:address=>[
nil,
nil,
{
:street=>"Reumannplatz 8",
:postcode=>"1020",
:phone=>"Vienna",
:altitude=>-1,
:geolocation=>[
"12.367464",
"48.204876"
]
}
]
}
Upon calling db.venues.save(new_object) what I would like the document to end up looking like is:
{
:_id=>BSON::ObjectId('4e73a30466ca1a1f56000001'),
:updated=>1316215099,
:address=>[ {
"street": "Rotenturmstrasse 8",
"postcode": "1020",
"phone": "Vienna",
"altitude": -1,
"geolocation": [
"11.367464",
"47.204876"
]
},
nil,
{
:street=>"Reumannplatz 8",
:postcode=>"1020",
:phone=>"Vienna",
:altitude=>-1,
:geolocation=>[
"12.367464",
"48.204876"
]
}
]
}
Instead it overwrites the entire array and ends up like this:
{
:_id=>BSON::ObjectId('4e73a30466ca1a1f56000001'),
:updated=>1316215099,
:address=>[
nil,
nil,
{
:street=>"Reumannplatz 8",
:postcode=>"1020",
:phone=>"Vienna",
:altitude=>-1,
:geolocation=>[
"12.367464",
"48.204876"
]
}
]
}
What’s the way to do it? I am trying to avoid multiple queries. Would it make things easier if the address array in the database was a hash instead?
To alter the data use mongodb modifiers.
In this case, you want to $push a new value to the array.