Definition. $exists. Syntax: { field: { $exists: <boolean> } } When <boolean> is true, $exists matches the documents that contain the field, including documents where the field value is null . If <boolean> is false, the query returns only the documents that do not contain the field. [
Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.
To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }
In MongoDB, we can perform text search using text index and $text operator. Text index: MongoDB proved text indexes that are used to find the specified text from the string content. Text indexes should be either a string or an array of string elements.
Use $ne
(for "not equal")
db.collection.find({ "fieldToCheck": { $exists: true, $ne: null } })
Suppose we have a collection like below:
{
"_id":"1234"
"open":"Yes"
"things":{
"paper":1234
"bottle":"Available"
"bottle_count":40
}
}
We want to know if the bottle field is present or not?
Ans:
db.products.find({"things.bottle":{"$exists":true}})
i find that this works for me
db.getCollection('collectionName').findOne({"fieldName" : {$ne: null}})
db.<COLLECTION NAME>.find({ "<FIELD NAME>": { $exists: true, $ne: null } })
This comment is written in 2021 and applies for MongoDB 5.X and earlier versions.
If you value query performance never use $exists (or use it only when you have a sparse index over the field that is queried. the sparse index should match the criteria of the query, meaning, if searching for $exists:true, the sparse index should be over field:{$exist:true} , if you are querying where $exists:true the sparse index should be over field:{$exist:false}
Instead use :
db.collection.find({ "fieldToCheck": { $ne: null } })
or
db.collection.find({ "fieldToCheck": { $eq: null } })
this will require that you include the fieldToCheck in every document of the collection, however - the performance will be vastly improved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With