UPDATE: I suggest reading my accepted answer, which gives you a different approach to this problem.
I have the following collection.
{
"_id" : ObjectId("51fa56408e843042c0c24e3d"),
"uniqDates" : [
ISODate("2013-07-30T18:30:00Z"),
ISODate("2013-07-31T18:30:00Z")
]
}
{
"_id" : ObjectId("51fa5648c424ea3e37199502"),
"events" : [
{
"eid" : 1,
"title" : "Event 1",
"start" : ISODate("2013-08-04T18:30:00Z")
},
{
"eid" : 2,
"title" : "Event 2",
"start" : ISODate("2013-08-08T18:30:00Z")
}
]
}
I want to update the document in the "events" array, if it exists (I want to check it by eid), if it does not exist, I want to insert this document.
I am currently doing this with two queries.
db.col.update({events: {$exists: 1}}, {$pull: {"events": {"eid": 2}}});
and
db.schedule.update({events: {$exists: 1}}, {$addToSet:
{"events": {"eid": 2, "title": "Event 4", "start": new Date(2013, 08, 02)}}});
Is there a way to do this with a single request? Something with an upsert operation.
source
share