[SERVER-15612] $in might cover "not exists" with a special value Created: 13/Oct/14  Updated: 09/Jul/16  Resolved: 13/Oct/14

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

Type: New Feature Priority: Major - P3
Reporter: Mustafa Dokumac? Assignee: Unassigned
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Participants:

 Description   

Example Data:

{field1: 'String1', field2: 'String2'},
{field1: 'String3', field2: 'String4'},
{field1: 'String5'}

Example Query:

db.collection.find({
  field2: {
    $in: ['String2', {$exists: false}]
  }
})

Example Resultset:

{field1: 'String1', field2: 'String2'},
{field1: 'String5'}



 Comments   
Comment by Mustafa Dokumac? [ 13/Oct/14 ]

Thank you for quick respond and helping me. You can avoid this kind of time stealing issues / questions by documenting the behaviour at one of these pages:

http://docs.mongodb.org/manual/reference/operator/query/in/
http://docs.mongodb.org/manual/reference/operator/query/exists/

There is an example for "exists and not equal to one of these" ($exists & $nin) but no example for "not exists or equal to one of these".

Have a nice day.

Comment by Thomas Rueckstiess [ 13/Oct/14 ]

Hi Mustafa,

While you cannot nest special operators inside an $in query, you can achieve this behavior (with a slight caveat) with the following query:

> db.collection.find({field2: {$in: ['String2', null]}})
{ "_id" : ObjectId("543bed4e93b9737a7384412c"), "field1" : "String1", "field2" : "String2" }
{ "_id" : ObjectId("543bed5c93b9737a7384412e"), "field1" : "String5" }

Instead of {$exists: false}, you can use the value null, which will also return non-existing fields.

The caveat is that it will also return documents that have the value field2 set to null explicitly. If you treat null and "non-existing" values as equivalent in your schema however, then this query does what you're asking for.

Regards,
Thomas

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