Wandang
Wandang

Reputation: 952

MongoDB update query multiple criteria

My user object contains a timeslots array with timeslotobjects (as seen below).

"username" : "bla",
"timeslots" : [
        {
                "lab" : 0,
                "timestamp" : 1495494000000,
                "durationfactor" : 4
        },
        {
                "lab" : 1,
                "timestamp" : 1495494000000,
                "durationfactor" : 4
        },
        {
                "lab" : 3,
                "timestamp" : 1495508400000,
                "durationfactor" : 4
        }

When I update those objects I get a wierd outlier case.

My update query (outlier case example):

db.users.update(
    {"timeslots.timestamp" : 1495494000000, "timeslots.lab": 1},
    { $set: {"timeslots.$.timestamp" : 1495508400000,"timeslots.$.durationfactor" : 4}} 
    ,false 
    ,true
);

Basically it checks (at least it should) if timestamp and lab are equal to a specific value. This combination is unique (labs cannot overlap on the same timestamp , they are "in use")

This works well except if I have two different labs on the same timestamp.

In the provided example I would expect lab 1 to be updated to the time of lab 3. But the result is lab 0 will be updated instead.

This behavior does not occur if there are two different timestamps with the same lab (inverse case). So I am really dumbfounded right now.

I tried to use {"$and": as well to force the combined query criteria which did not help.

I am assuming that the update query just updates the first element of the timeslots array, but I have no clue how to fix that.

Upvotes: 1

Views: 2364

Answers (1)

Dinesh undefined
Dinesh undefined

Reputation: 5546

$elemMatch

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

db.users.update(
    {"timeslots" : { "$elemMatch":{"timestamp": 1495494000000, "lab": 1}}},
    { $set: {"timeslots.$.timestamp" : 1495508400000,"timeslots.$.durationfactor" : 4}} 
    ,false 
    ,true
);

Upvotes: 1

Related Questions