查询空字段或缺少字段

MongoDB 中的不同查询运算符对null值的处理方式不同。

Mongo Shell
Compass
Python
Java (Sync)
Node.js
PHP
Motor
Java (Async)
C#
Perl
Ruby
Scala

This page provides examples of operations that query for null values using the db.collection.find() method in the mongo shell. The examples on this page use the inventory collection. To populate the inventory collection, run the following:

db.inventory.insertMany([
   { _id: 1, item: null },
   { _id: 2 }
])

You can run the operation in the web shell below:

MongoDB Web Shell

This page provides examples of operations that query for null values using MongoDB Compass. The examples on this page use the inventory collection. Populate the inventory collection with the following documents:

[
   { _id: 1, item: null },
   { _id: 2 }
]

For instructions on inserting documents in MongoDB Compass, see Insert Documents.

This page provides examples of operations that query for null values using the pymongo.collection.Collection.find() method in the PyMongo Python driver. The examples on this page use the inventory collection. To populate the inventory collection, run the following:

Important

You must use None with the PyMongo Python driver to query for null or missing fields in MongoDB.

db.inventory.insert_many([{"_id": 1, "item": None}, {"_id": 2}])

This page provides examples of operations that query for null values using the com.mongodb.client.MongoCollection.find method in the MongoDB Java Synchronous Driver.

Tip

The driver provides com.mongodb.client.model.Filters helper methods to facilitate the creation of filter documents. The examples on this page use these methods to create the filter documents.

The examples on this page use the inventory collection. To populate the inventory collection, run the following:

collection.insertMany(asList(
        Document.parse("{'_id': 1, 'item': null}"),
        Document.parse("{'_id': 2}")
));

This page provides examples of operations that query for null values using the Collection.find() method in the MongoDB Node.js Driver. The examples on this page use the inventory collection. To populate the inventory collection, run the following:

await db.collection('inventory').insertMany([{ _id: 1, item: null }, { _id: 2 }]);

This page provides examples of operations that query for null values using the MongoDB\Collection::find() method in the MongoDB PHP Library. The examples on this page use the inventory collection. To populate the inventory collection, run the following:

$insertManyResult = $db->inventory->insertMany([
    ['_id' => 1, 'item' => null],
    ['_id' => 2],
]);

This page provides examples of operations that query for null values using the motor.motor_asyncio.AsyncIOMotorCollection.find() method in the Motor driver. The examples on this page use the inventory collection. To populate the inventory collection, run the following:

Important

You must use None with the Motor driver to query for null or missing fields in MongoDB.

await db.inventory.insert_many([{"_id": 1, "item": None}, {"_id": 2}])

This page provides examples of operations that query for null values using the com.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 the following:

Publisher<Success> insertManyPublisher = collection.insertMany(asList(
        Document.parse("{'_id': 1, 'item': null}"),
        Document.parse("{'_id': 2}")
));

This page provides examples of operations that query for null values using the MongoCollection.Find() method in the MongoDB C# Driver. The examples on this page use the inventory collection. To populate the inventory collection, run the following:

Important

You must use BsonNull.Value with the MongoDB C# driver to query for null or missing fields in MongoDB.

var documents = new[]
{
    new BsonDocument { { "_id", 1 }, { "item", BsonNull.Value } },
    new BsonDocument { { "_id", 2 } }
};
collection.InsertMany(documents);

This page provides examples of operations that query for null values using the MongoDB::Collection::find() method in the MongoDB Perl Driver. The examples on this page use the inventory collection. To populate the inventory collection, run the following:

Important

You must use undef with the MongoDB Perl driver to query for null or missing fields in MongoDB.

$db->coll("inventory")->insert_many( [ { _id => 1, item => undef }, { _id => 2 } ] );

This page provides examples of operations that query for null values using the Mongo::Collection#find() method in the MongoDB Ruby Driver. The examples on this page use the inventory collection. To populate the inventory collection, run the following:

Important

You must use nil with the MongoDB Ruby driver to query for null or missing fields in MongoDB.

client[:inventory].insert_many([{ _id: 1, item: nil },
                                { _id: 2 }])

This page provides examples of operations that query for null values using the collection.find() method in the MongoDB Scala Driver. The examples on this page use the inventory collection. To populate the inventory collection, run the following:

Important

You must use BsonNull() with the MongoDB Scala driver to query for null or missing fields in MongoDB.

collection.insertMany(Seq(
  Document("""{"_id": 1, "item": null}"""),
  Document("""{"_id": 2}""")
)).execute()

Equality Filter

Mongo Shell
Compass
Python
Java (Sync)
Node.js
PHP
Motor
Java (Async)
C#
Perl
Ruby
Scala

The { item : null } query matches documents that either contain the item field whose value is null or that do not contain the item field.

db.inventory.find( { item: null } )

The { item : null } query matches documents that either contain the item field whose value is null or that do not contain the item field.
Copy the following query filter document into the query bar and click Find:

{ item: null }

../../_images/compass-find-null-field.png

The { item : None } query matches documents that either contain the item field whose value is null or that do not contain the item field.

cursor = db.inventory.find({"item": None})

The eq("item", null) query matches documents that either contain the item field whose value is null or that do not contain the item field.

FindIterable<Document> findIterable = collection.find(eq("item", null));

The { item : null } query matches documents that either contain the item field whose value is null or that do not contain the item field.

const cursor = db.collection('inventory').find({
  item: null
});

The [ item => undef ] query matches documents that either contain the item field whose value is null or that do not contain the item field.

$cursor = $db->inventory->find(['item' => null]);

The { item : None } query matches documents that either contain the item field whose value is null or that do not contain the item field.

cursor = db.inventory.find({"item": None})

The eq("item", null) query matches documents that either contain the item field whose value is null or that do not contain the item field.

FindPublisher<Document> findPublisher = collection.find(eq("item", null));

The Eq("item", BsonNull.Value) query using the FilterDefinitionBuilder.Eq() method matches documents that either contain the item field whose value is null or that do not contain the item field.

var filter = Builders<BsonDocument>.Filter.Eq("item", BsonNull.Value);
var result = collection.Find(filter).ToList();

The { item => undef } query matches documents that either contain the item field whose value is null or that do not contain the item field.

$cursor = $db->coll("inventory")->find( { item => undef } );

The { item => nil } query matches documents that either contain the item field whose value is nil or that do not contain the item field.

client[:inventory].find(item: nil)

The equal("item", BsonNull) query matches documents that either contain the item field whose value is null or that do not contain the item field.

var findObservable = collection.find(equal("item", BsonNull()))

该查询返回集合中的两个文档。

Type Check

Mongo Shell
Compass
Python
Java (Sync)
Node.js
PHP
Motor
Java (Async)
C#
Perl
Ruby
Scala

The { item : { $type: 10 } } query 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 ) :

db.inventory.find( { item : { $type: 10 } } )

The { item : { $type: 10 } } query 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 ) :
Copy the following query filter document into the query bar and click Find:

{ item : { $type: 10 } }

../../_images/compass-find-null-type-check.png

The { item : { $type: 10 } } query 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 ) :

cursor = db.inventory.find({"item": {"$type": 10}})

The type("item", BsonType.NULL) query 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 ) :

findIterable = collection.find(type("item", BsonType.NULL));

The { item : { $type: 10 } } query 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 ) :

const cursor = db.collection('inventory').find({
  item: { $type: 10 }
});

The [ item => [ $type => 10 ] ] query 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 ) :

$cursor = $db->inventory->find(['item' => ['$type' => 10]]);

The { item : { $type: 10 } } query 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 ) :

cursor = db.inventory.find({"item": {"$type": 10}})

The type("item", BsonType.NULL) query 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 ) :

findPublisher = collection.find(type("item", BsonType.NULL));

The Type("item", BsonType.Null) query using the FilterDefinitionBuilder.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 ) :

var filter = Builders<BsonDocument>.Filter.Type("item", BsonType.Null);
var result = collection.Find(filter).ToList();

The { item => { $type => 10 } } query 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 ) :

$cursor = $db->coll("inventory")->find( { item => { '$type' => 10 } } );

The { item => { $type => 10 } } query 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 ) :

client[:inventory].find(item: { '$type' => 10 })
findObservable = collection.find(bsonType("item", BsonType.NULL))

该查询仅返回item字段的值为null的文档。

Existence Check

Mongo Shell
Compass
Python
Java (Sync)
Node.js
PHP
Motor
Java (Async)
C#
Perl
Ruby
Scala

The { item : { $exists: false } } query matches documents that do not contain the item field:

db.inventory.find( { item : { $exists: false } } )

The { item : { $exists: false } } query matches documents that do not contain the item field:
Copy the following query filter document into the query bar and click Find:

Note

{ item : { $exists: false } }

../../_images/compass-find-null-existence-check.png

The { item : { $exists: False } } query matches documents that do not contain the item field:

cursor = db.inventory.find({"item": {"$exists": False}})

The exists("item", false) query matches documents that do not contain the item field:

findIterable = collection.find(exists("item", false));

The { item : { $exists: false } } query matches documents that do not contain the item field:

const cursor = db.collection('inventory').find({
  item: { $exists: false }
});

The [ item => [ $exists => false ] ] query matches documents that do not contain the item field:

$cursor = $db->inventory->find(['item' => ['$exists' => false]]);

The { item : { $exists: False } } query matches documents that do not contain the item field:

cursor = db.inventory.find({"item": {"$exists": False}})

The exists("item", false) query matches documents that do not contain the item field:

findPublisher = collection.find(exists("item", false));

The Exists("item", false) query using the FilterDefinitionBuilder.Exists() method matches documents that do not contain the item field:

var filter = Builders<BsonDocument>.Filter.Exists("item", false);
var result = collection.Find(filter).ToList();

The { item => { $exists => false } } query matches documents that do not contain the item field:

# For boolean values, use boolean.pm for 'true' and 'false'
$cursor = $db->coll("inventory")->find( { item => { '$exists' => false } } );

The { item => { $exists => false } } query matches documents that do not contain the item field:

client[:inventory].find(item: { '$exists' => false })

The exists("item", exists = false) query matches documents that do not contain the item field:

findObservable = collection.find(exists("item", exists = false))

该查询仅返回不包含item字段的文档。

See also

$type$exists运算符的参考文档。