Hi,
I'm a MongoDB newbie and wanted to ask how to write an update command involving upsert and list.
Basically I want to accomplish something like this:
{"_id" : ObjectId("4c28f62cbf8544c60506f11d"),
"some_other_data":"goes here",
"trips": [
{"name": "2010-05-10",
"loc": [{"lat":21.321231, "lng": 16.8783234, "updated_at": "Mon May 10 2010 15:24:35"},
{"lat":21.321231, "lng": 16.8783234, "updated_at": "Mon May 10 2010 15:24:24"}]
},
{"name": "2010-05-08",
"loc": [{"lat":21.324239, "lng": 16.8735234, "updated_at": "Mon May 8 2010 11:18:05"},
{"lat":21.311234, "lng": 16.8743271, "updated_at": "Mon May 8 2010 11:17:55"},
{"lat":21.321238, "lng": 16.8782219, "updated_at": "Mon May 8 2010 11:17:45"}]
}
]}
Note that:
- You supply a trip name and the current location
- If the trip does not exist already, it needs to be created
- trips.name should be unique so that if it exists, you append to the location array
This is the query I wrote combining the positional operator with $push.
db.mycollection.update({"application_id": "MyTestApp",
"trips.name": "2010-05-10"},
{$push: {'trips.$.loc': {"lat":11, "lng":11} }},
true);
But this results in data like this:
> db.mycollection.find({"application_id":"MyTestApp"})
{ "_id" : ObjectId("4c29044ebf8544c60506f11f"),
"application_id" : "MyTestApp",
"trips" : { "$" : { "loc" : [ { "lat" : 11, "lng" : 11 } ] },
"name" : "2010-05-10" }
}
You can see that
- "trips" is not an array
- it took "$" literally and created a key with that (doh!)
So far I've been pretty happy with MongoDB, but there's definitely a steep learning curve with writing complicated queries.
Any feedback will be appreciated.
Thanks in advance, Amie