Docs HomeMongoDB Manual

Query for Null or Missing Fields查询Null或缺少的字段


➤ Use the Select your language drop-down menu in the upper-right to set the language of the following examples.


Different query operators in MongoDB treat null values differently.MongoDB中不同的查询运算符对null值的处理方式不同。

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. Connect to a test database in your MongoDB instance then create the inventory collection:

Important

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

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

Equality Filter

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 query returns both documents in the collection.

Type Check

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 (BSON Type 10):

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

The query returns only the document where the item field has a value of null.

Existence Check

The following example queries for documents that do not contain a field. [1]

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

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

The query only returns the document that does not contain the item field.

Tip

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, see Query for Null or Missing Fields.