[SERVER-27767] Positional $ operator works unexpectedly with $and query Created: 20/Jan/17  Updated: 23/Jan/17  Resolved: 20/Jan/17

Status: Closed
Project: Core Server
Component/s: Querying
Affects Version/s: 3.4.1
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: Dima Tolkach Assignee: Mark Agarunov
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Operating System: ALL
Participants:

 Description   

I have next document:

{ 
    "_id" : ObjectId("58821b8100e83a84ae110fbd"), 
    "a" : [ { "id" : 4, "group" : "a", "k" : "v1" },
              { "id" : 4, "group" : "b", "k" : "v2" } ] 
} 

and I want to replace 'v2' by 'v_new' using $set and $and in the query:

update({$and: [{'a.group': 'b'}, {'a.id': 4}] }, {'$set': {'a.$.k': 'v_new'} })

But it replaces 'v1' by 'v_new' ($ refers to wrong element of array 'a').



 Comments   
Comment by Kelsey Schubert [ 23/Jan/17 ]

Hi chakmidlot,

The first element satisfies part of the query criteria ('a.id': 4) and so $ refers to that element.

As Mark described, the $elemMatch operator will provide the desired behavior.

Kind regards,
Thomas

Comment by Dima Tolkach [ 20/Jan/17 ]

Hi Mark

Sorry for wrong project choosing.

The query matches element 1 only, but $ refers to element 0.

Thanks,
Dima

Comment by Mark Agarunov [ 20/Jan/17 ]

Hello chakmidlot,

Thank you for the report. Looking at the output you've provided, this is expected behavior. The semantics of the $ operator are further explained in the documentation:

the positional $ operator acts as a placeholder for the first element that matches the query document

As your query will match both elements in the array, the first element is used.

However, the $elemMatch operator, for which documentation can be found here, will only return an element that matches all of the specified criteria, which should provide the desired behavior.

Please note that SERVER project is for reporting bugs or feature suggestions for the MongoDB server. For MongoDB-related support discussion please post on the mongodb-user group or Stack Overflow with the mongodb tag. A question like this involving more discussion would be best posted on the mongodb-user group.

Thanks,
Mark

Generated at Thu Feb 08 04:16:10 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.