[SERVER-12496] $elemMatch on subarrays returns different results in 2.4 vs 2.6 Created: 27/Jan/14  Updated: 06/Dec/22  Resolved: 05/Jul/19

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

Type: Bug Priority: Major - P3
Reporter: Andrew Emil (Inactive) Assignee: Backlog - Query Team (Inactive)
Resolution: Done Votes: 1
Labels: 26qa, query-44-grooming
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Attachments: File server12496.js    
Issue Links:
Related
Assigned Teams:
Query
Operating System: ALL
Participants:

 Description   

I don't yet understand the behavior surrounding this issue, but have generated a small reproduction.

In 2.5:

> x
{ "_id" : 0, "a" : [ [ { "a" : [ 1 ] } ] ] }
> db.mytest.insert(x)
SingleWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 1,
        "nUpserted" : 0,
        "nUpdated" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})
> db.mytest.find({"a.0": {$elemMatch: {a: 1}}})
{ "_id" : 0, "a" : [ [ { "a" : [ 1 ] } ] ] }
> db.runCommand({buildinfo: 1})
{
        "version" : "2.5.5-pre-",
        "gitVersion" : "4e62d347f090ce1afd91dc59b3db2fab8f930bc0",
        "OpenSSLVersion" : "",
        "sysInfo" : "Darwin Andrew-Emil-MacBook-Pro.local 12.4.0 Darwin Kernel Version 12.4.0: Wed May  1 17:57:12 PDT 2013; root:xnu-2050.24.15~1/RELEASE_X86_64 x86_64 BOOST_LIB_VERSION=1_49",
        "loaderFlags" : "-fPIC -pthread -Wl,-bind_at_load -mmacosx-version-min=10.6",
        "compilerFlags" : "-Wnon-virtual-dtor -Woverloaded-virtual -fPIC -fno-strict-aliasing -ggdb -pthread -Wall -Wsign-compare -Wno-unknown-pragmas -Winvalid-pch -Werror -pipe -O3 -Wno-unused-function -Wno-deprecated-declarations -mmacosx-version-min=10.6",
        "allocator" : "tcmalloc",
        "versionArray" : [
                2,
                5,
                5,
                -100
        ],
        "javascriptEngine" : "V8",
        "bits" : 64,
        "debug" : false,
        "maxBsonObjectSize" : 16777216,
        "ok" : 1
}
 

But in 2.4.9 the document is not returned:

> x
{ "_id" : 0, "a" : [ [ { "a" : [ 1 ] } ] ] }
> mydb.mytest.insert(x)
> mydb.mytest.find({"a.0": {$elemMatch: {a: 1}}})



 Comments   
Comment by David Storch [ 05/Jul/19 ]

The behavior in versions >= 2.6 seems correct to me, so I'm closing this ticket as "Works as Designed". The "a.0" path selects the nested array:

[ { "a" : [ 1 ] } ]

The predicate {$elemMatch: {a: 1}} is then applied to the nested array. The $elemMatch matches arrays which contain a document that matches the predicate {a: 1}. Therefore, the document as a whole matches iff the subdocument {a: [1]} matches. Indeed, the subdocument matches due to the implicit array traversal behavior of the "a == 1" predicate.

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