Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB query: field either does not exist or has specific value

Tags:

I'd like to query a mongo collection for records which either don't have a value for a field named 'scheme', or explicitly have the value 'http' for 'scheme'. Sounds pretty easy, but this problem has proved more complex than it first appears.

Since db.collection.find({'scheme': None}) returns all records where 'scheme' is undefined (no index field), I initially assumed the following would work:

db.collection.find({'scheme': {'$in': ['http', None]}})

However, this seems to exclude values in which 'scheme' is undefined, so I can only assume it is searching for records where scheme is either 'http', or explicitly defined to be None. This seems to be a bit counterintuitive, but there we have it. My second attempt was the following:

db.collection.find( {'$or': [{'scheme': {'$exists': False}}, {'scheme': 'http'}]})

This also excludes result where scheme is undefined. This time, I can't even think of a logical reason why this is failing.

Any ideas why this is failing, and how I can get it to work as desired?

Thanks

EDIT: Just thought I'd note that I'm performing this query through Python (pymongo), which explains the None (over Javascript's null)

like image 357
majackson Avatar asked Jan 05 '11 15:01

majackson


People also ask

How do you check field is exist or not in MongoDB?

In MongoDB, we can check the existence of the field in the specified collection using the $exists operator. When the value of $exists operator is set to true, then this operator matches the document that contains the specified field(including the documents where the value of that field is null).

How do I display null values in MongoDB?

MongoDB fetch documents containing 'null' If we want to fetch documents from the collection "testtable" which contains the value of "interest" is null, the following mongodb command can be used : >db. testtable. find( { "interest" : null } ).

How do I ignore NULL values in MongoDB?

Solution 1: In case preservation of all null values[] or null fields in the array itself is not necessary. Filter out the not null elements using $filter , the ( all null elements) array would be empty, filter that out from documents using $match then $sort on values .

IS NOT NULL condition in MongoDB?

Basically “not null” constraint is used to display the document without null from the collection as per our requirement means as per our requirement we can choose any field name with a different comparison operator and Boolean operator. Basically, we can use the $exists a method to implement the not null in MongoDB.


1 Answers

Resolved: This is apparently an issue of my version of mongodb (1.4.4), the issue is solved in 1.6.5.

like image 168
majackson Avatar answered Oct 13 '22 21:10

majackson