Query for Null or Missing Fields
This page provides examples in:
Different query operators in MongoDB treat null
values differently.
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
This page provides examples of operations that query for null
values using thedb.collection.find()
method in themongo
shell. The examples on this page use theinventory
collection. To populate the inventory
collection, run the following:
This page provides examples of operations that query for null
values usingMongoDB Compass. The examples on thispage use the inventory
collection. Populate theinventory
collection with the following documents:
This page provides examples of operations that query for null
values using thepymongo.collection.Collection.find()
method in thePyMongoPython driver. The examples on this page use the inventory
collection. To populate the inventory
collection, run thefollowing:
This page provides examples of operations that query for null
values using thecom.mongodb.client.MongoCollection.find method in the MongoDBJava Synchronous Driver.
Tip
The driver provides com.mongodb.client.model.Filtershelper methods to facilitate the creation of filterdocuments. The examples on this page use these methods tocreate the filter documents.
The examples on this page use the inventory
collection. To populate the inventory
collection, run thefollowing:
This page provides examples of operations that query for null
values using theCollection.find() method inthe MongoDB Node.js Driver.The examples on this page use the inventory
collection. Topopulate the inventory
collection, run the following:
This page provides examples of operations that query for null
values using theMongoDB\Collection::find()
method in theMongoDB PHP Library.The examples on this page use the inventory
collection. Topopulate the inventory
collection, run the following:
This page provides examples of operations that query for null
values using themotor.motor_asyncio.AsyncIOMotorCollection.find()
method in the Motordriver. The examples on this page use the inventory
collection. To populate the inventory
collection, run thefollowing:
This page provides examples of operations that query for null
values using thecom.mongodb.reactivestreams.client.MongoCollection.find)method in the MongoDB Java Reactive Streams Driver.
The examples on this page use the inventory
collection. To populate the inventory
collection, run thefollowing:
This page provides examples of operations that query for null
values using theMongoCollection.Find()method in theMongoDB C# Driver.The examples on this page use the inventory
collection. Topopulate the inventory
collection, run the following:
This page provides examples of operations that query for null
values using theMongoDB::Collection::find() methodin theMongoDB Perl Driver.The examples on this page use the inventory
collection. Topopulate the inventory
collection, run the following:
This page provides examples of operations that query for null
values using theMongo::Collection#find()method in theMongoDB Ruby Driver.The examples on this page use the inventory
collection. Topopulate the inventory
collection, run the following:
This page provides examples of operations that query for null
values using thecollection.find()(implicite:org.mongodb.scala.bson.DefaultHelper.DefaultsTo[C,TResult],implicitct:scala.reflect.ClassTag[C]):org.mongodb.scala.FindObservable[C]) methodin theMongoDB Scala Driver.The examples on this page use the inventory
collection. Topopulate the inventory
collection, run the following:
This page provides examples of operations that query for null
values using theCollection.Findfunction in theMongoDB Go Driver.The examples on this page use the inventory
collection. Topopulate the inventory
collection, run the following:
- Python
- Motor
- C#
- Perl
- Ruby
- Other
- Scala
- Go
Important
Use None
with the PyMongo Python driver toquery for null
or missing fields in MongoDB.
Important
Use None
with the Motor driver toquery for null
or missing fields in MongoDB.
Important
Use BsonNull.Value
with the MongoDB C# driver toquery for null
or missing fields in MongoDB.
Important
Use undef
with the MongoDB Perl driver toquery for null
or missing fields in MongoDB.
Important
Use nil
with the MongoDB Ruby driver toquery for null
or missing fields in MongoDB.
Important
Use BsonNull()
with the MongoDB Scala driver to queryfor null
or missing fields in MongoDB.
Important
Use nil
with the MongoDB Go driver toquery for null
or missing fields in MongoDB.
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
- db.inventory.insertMany([
- { _id: 1, item: null },
- { _id: 2 }
- ])
You can run the operation in the web shell below:
- [
- { _id: 1, item: null },
- { _id: 2 }
- ]
For instructions on inserting documents in MongoDB Compass, seeInsert Documents.
- db.inventory.insert_many([{"_id": 1, "item": None}, {"_id": 2}])
- collection.insertMany(asList(
- Document.parse("{'_id': 1, 'item': null}"),
- Document.parse("{'_id': 2}")
- ));
- await db.collection('inventory').insertMany([{ _id: 1, item: null }, { _id: 2 }]);
- $insertManyResult = $db->inventory->insertMany([
- ['_id' => 1, 'item' => null],
- ['_id' => 2],
- ]);
- await db.inventory.insert_many([{"_id": 1, "item": None}, {"_id": 2}])
- Publisher<Success> insertManyPublisher = collection.insertMany(asList(
- Document.parse("{'_id': 1, 'item': null}"),
- Document.parse("{'_id': 2}")
- ));
- var documents = new[]
- {
- new BsonDocument { { "_id", 1 }, { "item", BsonNull.Value } },
- new BsonDocument { { "_id", 2 } }
- };
- collection.InsertMany(documents);
- $db->coll("inventory")->insert_many( [ { _id => 1, item => undef }, { _id => 2 } ] );
- client[:inventory].insert_many([{ _id: 1, item: nil },
- { _id: 2 }])
- collection.insertMany(Seq(
- Document("""{"_id": 1, "item": null}"""),
- Document("""{"_id": 2}""")
- )).execute()
- docs := []interface{}{
- bson.D{
- {"_id", 1},
- {"item", nil},
- },
- bson.D{
- {"_id", 2},
- },
- }
- result, err := coll.InsertMany(context.Background(), docs)
Equality Filter
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
The { item : null }
query matches documents that eithercontain the item
field whose value is null
or thatdo not contain the item
field.
The { item : null }
query matches documents that eithercontain the item
field whose value is null
or thatdo not contain the item
field.
The { item : None }
query matches documents that eithercontain the item
field whose value is null
or thatdo not contain the item
field.
The eq("item", null)
query matches documents that eithercontain the item
field whose value is null
or thatdo not contain the item
field.
The { item : null }
query matches documents that eithercontain the item
field whose value is null
or thatdo not contain the item
field.
The [ item => undef ]
query matches documents that eithercontain the item
field whose value is null
or thatdo not contain the item
field.
The { item : None }
query matches documents that eithercontain the item
field whose value is null
or thatdo not contain the item
field.
The eq("item", null)
query matches documents that eithercontain the item
field whose value is null
or thatdo not contain the item
field.
The Eq("item", BsonNull.Value)
query using the FilterDefinitionBuilder.Eq() methodmatches documents that either contain the item
field whosevalue is null
or that do not contain the item
field.
The { item => undef }
query matches documents that eithercontain the item
field whose value is null
or thatdo not contain the item
field.
The { item => nil }
query matches documents that eithercontain the item
field whose value is nil
or thatdo not contain the item
field.
The equal("item", BsonNull)
query matches documents thateither contain the item
field whose value is null
_or_that do not contain the item
field.
The item => nil
query matches documents that eithercontain the item
field whose value is nil
or thatdo not contain the item
field.
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
- db.inventory.find( { item: null } )
Copy the following query filter document into thequery bar and clickFind:
- { item: null }
- cursor = db.inventory.find({"item": None})
- FindIterable<Document> findIterable = collection.find(eq("item", null));
- const cursor = db.collection('inventory').find({
- item: null
- });
- $cursor = $db->inventory->find(['item' => null]);
- cursor = db.inventory.find({"item": None})
- FindPublisher<Document> findPublisher = collection.find(eq("item", null));
- var filter = Builders<BsonDocument>.Filter.Eq("item", BsonNull.Value);
- var result = collection.Find(filter).ToList();
- $cursor = $db->coll("inventory")->find( { item => undef } );
- client[:inventory].find(item: nil)
- var findObservable = collection.find(equal("item", BsonNull()))
- cursor, err := coll.Find(
- context.Background(),
- bson.D{
- {"item", nil},
- })
The query returns both documents in the collection.
Type Check
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Go
The { item : { $type: 10 } }
query matches _only_documents that contain the item
field whose value isnull
; i.e. the value of the item
field is ofBSON Type Null
(type number 10
) :
The { item : { $type: 10 } }
query matches _only_documents that contain the item
field whose value isnull
; i.e. the value of the item
field is ofBSON Type Null
(type number 10
) :
The { item : { $type: 10 } }
query matches _only_documents that contain the item
field whose value isnull
; i.e. the value of the item
field is ofBSON Type Null
(type number 10
) :
The type("item", BsonType.NULL)
query matches _only_documents that contain the item
field whose value isnull
; i.e. the value of the item
field is ofBSON Type Null
(type number 10
) :
The { item : { $type: 10 } }
query matches _only_documents that contain the item
field whose value isnull
; i.e. the value of the item
field is ofBSON Type Null
(type number 10
) :
The [ item => [ $type => 10 ] ]
query matches _only_documents that contain the item
field whose value isnull
; i.e. the value of the item
field is ofBSON Type Null
(type number 10
) :
The { item : { $type: 10 } }
query matches _only_documents that contain the item
field whose value isnull
; i.e. the value of the item
field is ofBSON Type Null
(type number 10
) :
The type("item", BsonType.NULL)
query matches _only_documents that contain the item
field whose value isnull
; i.e. the value of the item
field is ofBSON Type Null
(type number 10
) :
The Type("item", BsonType.Null)
query using theFilterDefinitionBuilder.Type()method matches only documents that contain the item
field whose value is null
; i.e. the value of the item
field is of BSON Type Null
(type number 10
) :
The { item => { $type => 10 } }
query matches _only_documents that contain the item
field whose value isnull
; i.e. the value of the item
field is ofBSON Type Null
(type number 10
) :
The { item => { $type => 10 } }
query matches _only_documents that contain the item
field whose value isnull
; i.e. the value of the item
field is ofBSON Type Null
(type number 10
) :
The following query matches _only_documents that contain the item
field whose value is ofBSON Type Null
(type number 10
) :
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
- db.inventory.find( { item : { $type: 10 } } )
Copy the following query filter document into thequery bar and clickFind:
- { item : { $type: 10 } }
- cursor = db.inventory.find({"item": {"$type": 10}})
- findIterable = collection.find(type("item", BsonType.NULL));
- const cursor = db.collection('inventory').find({
- item: { $type: 10 }
- });
- $cursor = $db->inventory->find(['item' => ['$type' => 10]]);
- cursor = db.inventory.find({"item": {"$type": 10}})
- findPublisher = collection.find(type("item", BsonType.NULL));
- var filter = Builders<BsonDocument>.Filter.Type("item", BsonType.Null);
- var result = collection.Find(filter).ToList();
- $cursor = $db->coll("inventory")->find( { item => { '$type' => 10 } } );
- client[:inventory].find(item: { '$type' => 10 })
- findObservable = collection.find(bsonType("item", BsonType.NULL))
- cursor, err := coll.Find(
- context.Background(),
- bson.D{
- {"item", bson.D{
- {"$type", 10},
- }},
- })
The query returns only the document where the item
field has avalue of null
.
Existence Check
The following example queries for documents that do not contain afield. [1]
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
The { item : { $exists: false } }
query matches documentsthat do not contain the item
field:
The { item : { $exists: false } }
query matches documentsthat do not contain the item
field:
The { item : { $exists: False } }
query matches documentsthat do not contain the item
field:
The exists("item", false)
query matches documents thatdo not contain the item
field:
The { item : { $exists: false } }
query matches documentsthat do not contain the item
field:
The [ item => [ $exists => false ] ]
query matches documentsthat do not contain the item
field:
The { item : { $exists: False } }
query matches documentsthat do not contain the item
field:
The exists("item", false)
query matches documents that donot contain the item
field:
The Exists("item", false)
query using the FilterDefinitionBuilder.Exists()method matches documents that do not contain the item
field:
The { item => { $exists => false } }
query matches documentsthat do not contain the item
field:
The { item => { $exists => false } }
query matches documentsthat do not contain the item
field:
The exists("item", exists = false)
query matches documentsthat do not contain the item
field:
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
- db.inventory.find( { item : { $exists: false } } )
Copy the following query filter document into thequery bar and clickFind:
- { item : { $exists: false } }
- cursor = db.inventory.find({"item": {"$exists": False}})
- findIterable = collection.find(exists("item", false));
- const cursor = db.collection('inventory').find({
- item: { $exists: false }
- });
- $cursor = $db->inventory->find(['item' => ['$exists' => false]]);
- cursor = db.inventory.find({"item": {"$exists": False}})
- findPublisher = collection.find(exists("item", false));
- var filter = Builders<BsonDocument>.Filter.Exists("item", false);
- var result = collection.Find(filter).ToList();
- # For boolean values, use boolean.pm for 'true' and 'false'
- $cursor = $db->coll("inventory")->find( { item => { '$exists' => false } } );
- client[:inventory].find(item: { '$exists' => false })
- findObservable = collection.find(exists("item", exists = false))
- cursor, err := coll.Find(
- context.Background(),
- bson.D{
- {"item", bson.D{
- {"$exists", false},
- }},
- })
The query only returns the document that does not contain theitem
field.
See also
Reference documentation for the $type
and$exists
operators.
[1] | Starting in MongoDB 4.2, users can no longer use the query filter$type: 0 as a synonym for$exists:false . To query for null or missing fields, seeQuery for Null or Missing Fields. |