[SERVER-71254] Object $elemMatch should not match arrays under an array Created: 10/Nov/22  Updated: 07/Dec/23

Status: Open
Project: Core Server
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Task Priority: Major - P3
Reporter: Hana Pearlman Assignee: Backlog - Query Optimization
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Assigned Teams:
Query Optimization
Participants:

 Description   

ElemMatchObjectMatchExpression is supposed to match arrays which have an object element satisfying the sub-predicates. However, there are some edge cases where it will match arrays which have an array element satisfying the sub-predicates. For example:

> db.foo.find()
{ "_id" : 0, "a" : [ [ ] ] }
{ "_id" : 1, "a" : [ [ { "b" : 1 } ] ] }
{ "_id" : 2, "a" : [ { "b" : 1 } ] }
 
// Object $elemMatch with an empty object
> db.foo.find({a: {$elemMatch: {}}})
{ "_id" : 0, "a" : [ [ ] ] }
{ "_id" : 1, "a" : [ [ { "b" : 1 } ] ] }
{ "_id" : 2, "a" : [ { "b" : 1 } ] }
 
// Somewhat surprisingly, this is also an object $elemMatch
> db.foo.find({a: {$elemMatch: {$or: [{$alwaysTrue: 1}]}}})
{ "_id" : 0, "a" : [ [ ] ] }
{ "_id" : 1, "a" : [ [ { "b" : 1 } ] ] }
{ "_id" : 2, "a" : [ { "b" : 1 } ] }

The hypothesis is that this is a mistake due to this line, which returns true for both objects and arrays.

The current behavior is consistent across all of our query frameworks. The proposal is to change the behavior for all query frameworks so that ElemMatchObjectMatchExpression only matches nested objects:

> db.foo.find({a: {$elemMatch: {}}})
{ "_id" : 2, "a" : [ { "b" : 1 } ] }
 
> db.foo.find({a: {$elemMatch: {$or: [{$alwaysTrue: 1}]}}})
{ "_id" : 2, "a" : [ { "b" : 1 } ] }



 Comments   
Comment by Hana Pearlman [ 01/Dec/23 ]

Finally moving this ticket out of PM-3240 and into the QO triage queue as it's not specific to CQF. Updated the ticket description with my current understanding of the suggestion cc david.storch@mongodb.com

Generated at Thu Feb 08 06:18:28 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.