MongoDB - update documents in an array

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.

+1
source share
2 answers

UPDATE
, , . . Array Update . , . , . google. "idbentley" (16 ), . , .

, upsert . , .

{
        "_id" : ObjectId("51fa619a8e843042c0c24e46"),
        "uniqDates" : [
                ISODate("2013-07-30T18:30:00Z"),
                ISODate("2013-07-31T18:30:00Z")
        ]
}
{
        "_id" : ObjectId("51fa61b38e843042c0c24e47"),
        "eid" : 1,
        "title" : "Event 1",
        "start" : ISODate("2013-08-04T18:30:00Z")
}
{
        "_id" : ObjectId("51fa61b38e843042c0c24e48"),
        "eid" : 2,
        "title" : "Event 2",
        "start" : ISODate("2013-08-08T18:30:00Z")
}

:

db.schedule.find({"eid": {$exists: 1}});

:

db.schedule.find({"uniqDates": {$exists: 1}});

"upsert":

db.schedule.update({"eid": 3}, {"eid": 3, "title": "Event 3", 
                                "start": new Date(2013, 05, 06)}, true); 

.

0

, . , $query update, , EID .

db.col.update({"events.eid": 2}}, {$set: {"events.$.title: "Event 4", "events.$.start": new Date(2013, 08, 02}})

, , .

+1

All Articles