[SERVER-10690] $exists query behaves incorrectly in subdocuments Created: 06/Sep/13  Updated: 06/Sep/13  Resolved: 06/Sep/13

Status: Closed
Project: Core Server
Component/s: None
Affects Version/s: 2.2.4, 2.4.5
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: Christian Sturm Assignee: Unassigned
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Operating System: ALL
Steps To Reproduce:

> db.test.insert({obj:{prop:null}})
> db.test.findOne()
{
"_id" : ObjectId("52298b4aaa95c6f468712074"),
"obj" :

{ "prop" : null }

}
> db.test.findOne({"obj.prop":{$exists: true}})
{
"_id" : ObjectId("52298b4aaa95c6f468712074"),
"obj" :

{ "prop" : null }

}

Participants:

 Description   

According to the documentation[1] "Documents that contain the field but has the value null are not returned."

This doesn't appear to be true, if one is querying against subdocuments.

[1] http://docs.mongodb.org/manual/reference/operator/exists/



 Comments   
Comment by Scott Hernandez (Inactive) [ 06/Sep/13 ]

That sentence is a little misleading since it refers to the {{ $exists: true }} case.

Only fields which do not exist (no matter what value they contain) meet the $exists:false criteria. If they have any value, including null, they meet the meet the requirement of existing ($exists:true).

> db.exists.save({_id:1, a:1, b:{a:1, c:null}, c:null})
> db.exists.find({a:{$exists:false}})
> db.exists.find({c:{$exists:false}})
> db.exists.find({c:{$exists:true}})
{ "_id" : 1, "a" : 1, "b" : { "a" : 1, "c" : null }, "c" : null }
> db.exists.find({"b.c":{$exists:true}})
{ "_id" : 1, "a" : 1, "b" : { "a" : 1, "c" : null }, "c" : null }
> db.exists.find({"b.c":{$exists:false}})

We have cleaned up the docs to make this clear.

Comment by Christian Sturm [ 06/Sep/13 ]

A workaround would be using "$ne: null".

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