Database Manual / CRUD Operations / Query

Query for Null or Missing Fields查询空白或缺失字段

You can query for null or missing fields in MongoDB using the following methods:您可以使用以下方法查询MongoDB中的null或缺失字段:


Use the Select your language drop-down menu in the upper-right to set the language of the following examples or select MongoDB Compass.使用右上角的“选择语言”下拉菜单设置以下示例的语言,或选择MongoDB Compass。


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

MongoDB Shell

This page provides examples of operations that query for null values using the db.collection.find() method in mongosh.本页提供了使用mongosh中的db.collection.find()方法查询空值的操作示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

Compass

This page provides examples of operations that query for null values using MongoDB Compass.本页提供了使用MongoDB Compass查询空值的操作示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

C

This page provides examples of operations that query for null values using mongoc_collection_find_with_opts.本页提供了使用mongoc_collection_find_with_opts查询null值的操作示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

C#

This page provides examples of operations that query for null values using the MongoCollection.Find() method in the MongoDB C# Driver.本页提供了使用MongoDB C#驱动程序中的MongoCollection.Find()方法查询空值的操作示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

Go

This page provides examples of operations that query for null values using the Collection.Find function in the MongoDB Go Driver.本页提供了使用MongoDB Go驱动程序中的Collection.Find函数查询空值的操作示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

Java(Async)

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.此页面提供了使用MongoDB Java Reactive Streams驱动程序中的com.mongodb.reactivestreams.client.MongoCollection.find方法查询空值的操作示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

Java(Sync)

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.本页提供了使用MongoDB Java同步驱动程序中的com.mongodb.client.MongoCollection.find方法查询空值的操作示例。

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.该驱动程序提供了com.mongodb.client.model.Filters辅助方法,以方便创建筛选器文档。本页上的示例使用这些方法创建筛选文档。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

Kotlin(Coroutine)

This page provides examples of operations that query for null values by using the MongoCollection.find() method in the MongoDB Kotlin Coroutine Driver.本页提供了使用MongoDB Kotlin协程驱动程序中的MongoCollection.find()方法查询null值的操作示例。

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.该驱动程序提供了com.mongodb.client.model.Filters辅助方法,以方便创建筛选器文档。本页上的示例使用这些方法创建筛选文档。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

Motor

This page provides examples of operations that query for null values using the motor.motor_asyncio.AsyncIOMotorCollection.find method in the Motor driver.此页面提供了使用Motor驱动程序中的motor.motor_asyncio.AsyncIOMotorCollection.find方法查询null值的操作示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:

Node.js

This page provides examples of operations that query for null values using the Collection.find() method in the MongoDB Node.js Driver.本页提供了使用MongoDB Node.js驱动程序中的Collection.find()方法查询null值的操作示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

PHP

This page provides examples of operations that query for null values using the MongoDB\\Collection::find() method in the MongoDB PHP Library.本页提供了使用MongoDB PHP库中的MongoDB\\Collection::find()方法查询null值的操作示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

Python

This page provides examples of operations that query for null values using the pymongo.collection.Collection.find method in the PyMongo Python driver.本页提供了使用PyMongo Python驱动程序中的pymongo.collection.Collection.find方法查询null值的操作示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

Ruby

This page provides examples of operations that query for null values using the Mongo::Collection#find() method in the MongoDB Ruby Driver.本页提供了使用MongoDB Ruby驱动程序中的Mongo::Collection#find()方法查询null值的操作示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

scala

This page provides examples of operations that query for null values using the collection.find() method in the MongoDB Scala Driver.本页提供了使用MongoDB Scala驱动程序中的collection.find()方法查询null值的操作示例。

The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:此页面上的示例使用inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:

C

Important

Use BCON_NULL with the MongoDB C driver to query for null or missing fields in MongoDB.使用BCON_NULL和MongoDB C驱动程序查询MongoDB中的null字段或缺失字段。

C#

Important

Use BsonNull.Value with the MongoDB C# driver to query for null or missing fields in MongoDB.在MongoDB C#驱动程序中使用BsonNull.Value查询MongoDB中的null字段或缺失字段。

Go

Important

Use nil with the MongoDB Go driver to query for null or missing fields in MongoDB.在MongoDB Go驱动程序中使用nil来查询MongoDB中的null或缺失字段。

Kotlin(Coroutine)

Important

Use null with the Kotlin Coroutine driver to query for null or missing fields in MongoDB.在Kotlin Coroutine驱动程序中使用null来查询MongoDB中的null或缺失字段。

Motor

Important

Use None with the Motor driver to query for null or missing fields in MongoDB.在Motor驱动程序中使用None来查询MongoDB中的null或缺失字段。

Python

Important

Use None with the PyMongo Python driver to query for null or missing fields in MongoDB.在PyMongo Python驱动程序中使用None来查询MongoDB中的null或缺失字段。

Ruby

Important

Use nil with the MongoDB Ruby driver to query for null or missing fields in MongoDB.在MongoDB Ruby驱动程序中使用nil来查询MongoDB中的null或缺失字段。

scala

Important

Use BsonNull() with the MongoDB Scala driver to query for null or missing fields in MongoDB.在MongoDB Scala驱动程序中使用BsonNull()查询MongoDB中的null或缺失字段。

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

For instructions on inserting documents in MongoDB Compass, see Insert Documents.有关在MongoDB Compass中插入文档的说明,请参阅插入文档

C
mongoc_collection_t *collection;
mongoc_bulk_operation_t *bulk;
bson_t *doc;
bool r;
bson_error_t error;
bson_t reply;

collection = mongoc_database_get_collection (db, "inventory");
bulk = mongoc_collection_create_bulk_operation_with_opts (collection, NULL);
doc = BCON_NEW (
"_id", BCON_INT64 (1),
"item", BCON_NULL);

r = mongoc_bulk_operation_insert_with_opts (bulk, doc, NULL, &error);
bson_destroy (doc);
if (!r) {
MONGOC_ERROR ("%s\n", error.message);
goto done;
}

doc = BCON_NEW ("_id", BCON_INT64 (2));

r = mongoc_bulk_operation_insert_with_opts (bulk, doc, NULL, &error);
bson_destroy (doc);
if (!r) {
MONGOC_ERROR ("%s\n", error.message);
goto done;
}

/* "reply" is initialized on success or error */
r = (bool) mongoc_bulk_operation_execute (bulk, &reply, &error);
if (!r) {
MONGOC_ERROR ("%s\n", error.message);
}
C#
var documents = new[]
{
new BsonDocument { { "_id", 1 }, { "item", BsonNull.Value } },
new BsonDocument { { "_id", 2 } }
};
collection.InsertMany(documents);
Go
docs := []any{
bson.D{
{"_id", 1},
{"item", nil},
},
bson.D{
{"_id", 2},
},
}

result, err := coll.InsertMany(context.TODO(), docs)
Java(Async)
Publisher<Success> insertManyPublisher = collection.insertMany(asList(
Document.parse("{'_id': 1, 'item': null}"),
Document.parse("{'_id': 2}")
));
Java(Sync)
collection.insertMany(asList(
Document.parse("{'_id': 1, 'item': null}"),
Document.parse("{'_id': 2}")
));
Kotlin(Coroutine)
collection.insertMany(
listOf(
Document("_id", 1)
.append("item", null),
Document("_id", 2)
)
)
Motor
await db.inventory.insert_many([{"_id": 1, "item": None}, {"_id": 2}])
Node.js
await db.collection('inventory').insertMany([{ _id: 1, item: null }, { _id: 2 }]);
PHP
$insertManyResult = $db->inventory->insertMany([
['_id' => 1, 'item' => null],
['_id' => 2],
]);
Python
db.inventory.insert_many([{"_id": 1, "item": None}, {"_id": 2}])
Ruby
client[:inventory].insert_many([{ _id: 1, item: nil },
{ _id: 2 }])
scala
collection.insertMany(Seq(
Document("""{"_id": 1, "item": null}"""),
Document("""{"_id": 2}""")
)).execute()

Equality Filter相等筛选器

MongoDB Shell

The { item : null } query matches documents that either contain the item field whose value is null or that do not contain the item field.{ item : null }查询匹配包含值为nullitem字段或不包含item字段的文档。

Compass

The { item : null } query matches documents that either contain the item field whose value is null or that do not contain the item field.{ item : null }查询匹配包含值为nullitem字段或不包含item字段的文档。

C

The { item, BCON_NULL } query matches documents that either contain the item field whose value is null or that do not contain the item field.{ item, BCON_NULL }查询匹配包含值为NULLitem字段或不包含item字段的文档。

C#

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.使用FilterDefinitionBuilder.Eq()方法的Eq("item", BsonNull.Value)查询匹配包含值为nullitem字段或不包含item字段的文档。

Go

The item => nil query matches documents that either contain the item field whose value is nil or that do not contain the item field.item => nil查询匹配包含值为nil的item字段或不包含item字段的文档。

Java(Async)

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.

Java(Sync)

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.eq("item", null)查询匹配包含值为nullitem字段或不包含item字段的文档。

Kotlin(Coroutine)

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.eq("item", null)查询匹配包含值为nullitem字段或不包含item字段的文档。

Motor

The { item : None } query matches documents that either contain the item field whose value is null or that do not contain the item field.{ item : None }查询匹配包含值为nullitem字段或不包含item字段的文档。

Node.js

The { item : null } query matches documents that either contain the item field whose value is null or that do not contain the item field.{ item : null }查询匹配包含值为nullitem字段或不包含item字段的文档。

PHP

The [ item => undef ] query matches documents that either contain the item field whose value is null or that do not contain the item field.[ item => undef ]查询匹配包含值为nullitem字段或不包含item字段的文档。

Python

The { item : None } query matches documents that either contain the item field whose value is null or that do not contain the item field.{ item : None }查询匹配包含值为nullitem字段或不包含item字段的文档。

Ruby

The { item => nil } query matches documents that either contain the item field whose value is nil or that do not contain the item field.{ item => nil }查询匹配包含值为nilitem字段或不包含item字段的文档。

scala

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.equal("item", BsonNull)查询匹配包含值为nullitem字段或不包含item字段的文档。

MongoDB Shell
db.inventory.find( { item: null } )
Compass

Copy the following query filter document into the query bar and click Find:将以下查询筛选文档复制到“查询栏”中,然后单击“查找”:

{ item: null }
Query null value or missing field
C
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;

collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW ("item", BCON_NULL);
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);
C#
var filter = Builders<BsonDocument>.Filter.Eq("item", BsonNull.Value);
var result = collection.Find(filter).ToList();
Go
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"item", nil},
})
Java(Async)
FindPublisher<Document> findPublisher = collection.find(eq("item", null));
Java(Sync)
FindIterable<Document> findIterable = collection.find(eq("item", null));
Kotlin(Coroutine)
val findFlow = collection
.find(eq("item", null))
Motor
cursor = db.inventory.find({"item": None})
Node.js
const cursor = db.collection('inventory').find({
item: null
});
PHP
$cursor = $db->inventory->find(['item' => null]);
Python
cursor = db.inventory.find({"item": None})
Ruby
client[:inventory].find(item: nil)
scala
var findObservable = collection.find(equal("item", BsonNull()))

The query returns both documents in the collection.查询返回集合中的两个文档。

Non-Equality Filter非相等筛选器

To query for fields that exist and are not null, use the { $ne : null } filter. 要查询存在且不为null的字段,请使用{ $ne : null }筛选器。The { item : { $ne : null } } query matches documents where the item field exists and has a non-null value.{ item : { $ne : null } }查询匹配存在item字段且具有非null值的文档。

MongoDB Shell
db.inventory.find( { item: { $ne : null } } )
Compass
{ item: { $ne : null } }
C
filter = BCON_NEW ("item", BCON_NULL);
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);
C#
var filter = Builders<BsonDocument>.Filter.Ne("item", BsonNull.Value);
var result = collection.Find(filter).ToList();
Go
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"item", bson.D{"$ne": nil}},
})
Java(Async)
db.inventory.find( { item: { $ne : null} } )
Java(Sync)
collection.find(ne("item", null));
Kotlin(Coroutine)
collection.find(ne("item", null))
Motor
cursor = db.inventory.find( { "item": { "$ne": None } } )
Node.js
const cursor = db.collection('inventory')
.find({ item: { $ne : null }
});
PHP
$cursor = $db->inventory->find(['item' => ['$ne' => null ]]);
Python
cursor = db.inventory.find( { "item": { "$ne": None } } )
Ruby
client[:inventory].find(item: { '$ne' => nil })
scala
collection.find($ne("item", null));

Type Check类型检查

MongoDB Shell

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):{ item : { $type: 10 } }查询仅匹配包含值为nullitem字段的文档;即,item字段的值为BSON类型null(BSON类型10):

Compass

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):{ item : { $type: 10 } }查询仅匹配包含值为nullitem字段的文档;即,item字段的值为BSON类型null(BSON类型10):

C

The { item, { $type, BCON_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 (BSON Type 10):{ item, { $type, BCON_NULL } }查询仅匹配包含值为nullitem字段的文档;即,item字段的值为BSON类型null(BSON类型10):

C#

The Type("item", BsonType.Null) query using the FilterDefinitionBuilder.Type() method matches only documents that contain the item field whose value is null. 使用FilterDefinitionBuilder.Type()方法的Type("item", BsonType.Null)查询仅匹配包含值为nullitem字段的文档。The value of the item field is of BSON Typeitem字段的值为BSON类型 Null (BSON Type 10):

Go

The following query matches only documents that contain the item field whose value is of BSON Type Null (BSON Type 10):

Java(Async)

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

Java(Sync)

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

Java(Sync)

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

Kotlin(Coroutine)

The type("item", BsonType.NULL) query matches only documents that contain the item field whose value is null. This means the value of the item field is of BSON Type Null (BSON Type 10):

Motor

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):

Node.js

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):

PHP

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):

Python

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):

Ruby

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):

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

Copy the following query filter document into the query bar and click Find:将以下查询筛选文档复制到“查询栏”中,然后单击“查找”:

{ item : { $type: 10 } }
Find null type
C
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;

collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW (
"item", "{",
"$type", BCON_INT64 (10),
"}");
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);
C#
var filter = Builders<BsonDocument>.Filter.Type("item", BsonType.Null);
var result = collection.Find(filter).ToList();
Go
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"item", bson.D{
{"$type", 10},
}},
})
Java(Async)
findPublisher = collection.find(type("item", BsonType.NULL));
Java(Sync)
findIterable = collection.find(type("item", BsonType.NULL));
Kotlin(Coroutine)
val findFlow = collection
.find(type("item", BsonType.NULL))
Motor
cursor = db.inventory.find({"item": {"$type": 10}})
Node.js
const cursor = db.collection('inventory').find({
item: { $type: 10 }
});
PHP
$cursor = $db->inventory->find(['item' => ['$type' => 10]]);
Python
cursor = db.inventory.find({"item": {"$type": 10}})
Ruby
client[:inventory].find(item: { '$type' => 10 })
scala
findObservable = collection.find(bsonType("item", BsonType.NULL))

The query returns only the document where the item field has a value of null.查询仅返回item字段值为null的文档。

Existence Check存在性检查

The following example queries for documents that do not contain a field. 以下示例查询不包含字段的文档。[1]

MongoDB Shell

The { item : { $exists: false } } query matches documents that do not contain the item field:{ item : { $exists: false } }查询匹配不包含item字段的文档:

Compass

The { item : { $exists: false } } query matches documents that do not contain the item field:{ item : { $exists: false } }查询匹配不包含item字段的文档:

C

The { item, { $exists, BCON_BOOL (false) } } query matches documents that do not contain the item field:{ item, { $exists, BCON_BOOL (false) } }查询匹配不包含item字段的文档:

C#

The Exists("item", false) query using the FilterDefinitionBuilder.Exists() method matches documents that do not contain the item field:使用FilterDefinitionBuilder.Exists()方法的Exists("item", false)查询匹配不包含item字段的文档:

Java(Async)

The exists("item", false) query matches documents that do not contain the item field:exists("item", false)查询匹配不包含item字段的文档:

Java(Sync)

The exists("item", false) query matches documents that do not contain the item field:exists("item", false)查询匹配不包含item字段的文档:

Kotlin(Coroutine)

The exists("item", false) query matches documents that do not contain the item field:exists("item", false)查询匹配不包含item字段的文档:

Motor

The { item : { $exists: False } } query matches documents that do not contain the item field:{ item : { $exists: False } }查询匹配不包含item字段的文档:

Node.js

The { item : { $exists: false } } query matches documents that do not contain the item field:{ item : { $exists: false } }查询匹配不包含item字段的文档:

PHP

The [ item => [ $exists => false ] ] query matches documents that do not contain the item field:[ item => [ $exists => false ] ]查询匹配不包含item字段的文档:

Python

The { item : { $exists: False } } query matches documents that do not contain the item field:{ item : { $exists: False } }查询匹配不包含item字段的文档:

Ruby

The { item => { $exists => false } } query matches documents that do not contain the item field:{ item => { $exists => false } }查询匹配不包含item字段的文档:

scala

The exists("item", exists = false) query matches documents that do not contain the item field:exists("item", exists = false)查询匹配不包含item字段的文档:

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

Copy the following query filter document into the query bar and click Find:将以下查询筛选文档复制到“查询栏”中,然后单击“查找”:

{ item : { $exists: false } }
Query for null value
C
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;

collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW (
"item", "{",
"$exists", BCON_BOOL (false),
"}");
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);

Be sure to also clean up any open resources by calling the following methods, as appropriate:请确保根据需要调用以下方法来清理任何开放资源:

C#
var filter = Builders<BsonDocument>.Filter.Exists("item", false);
var result = collection.Find(filter).ToList();
Go
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"item", bson.D{
{"$exists", false},
}},
})
Java(Async)
findPublisher = collection.find(exists("item", false));
Java(Sync)
findIterable = collection.find(exists("item", false));
Kotlin(Coroutine)
val findFlow = collection
.find(exists("item", false))
Motor
cursor = db.inventory.find({"item": {"$exists": False}})
Node.js
const cursor = db.collection('inventory').find({
item: { $exists: false }
});
PHP
$cursor = $db->inventory->find(['item' => ['$exists' => false]]);
Python
cursor = db.inventory.find({"item": {"$exists": False}})
Ruby
client[:inventory].find(item: { '$exists' => false })
scala
findObservable = collection.find(exists("item", exists = false))

The query only returns the document that does not contain the item field.查询仅返回不包含item字段的文档。

Tip

Reference documentation for the $type and $exists operators.$type$exists运算符的参考文档。

[1] 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.用户不能再使用查询筛选器$type:0作为$exists:false的同义词。要查询空或缺少的字段,请参阅查询空或丢失的字段

Query for Null or Missing Fields with MongoDB Atlas使用MongoDB Atlas查询空字段或缺失字段

The example in this section uses the sample training dataset. 本节中的示例使用示例训练数据集To learn how to load the sample dataset into your MongoDB Atlas deployment, see Load Sample Data.要了解如何将示例数据集加载到MongoDB Atlas部署中,请参阅加载示例数据

To query for a null or missing field in MongoDB Atlas, follow these steps:要查询MongoDB Atlas中的null字段或缺失字段,请执行以下步骤:

1

In the MongoDB Atlas UI, go to the Clusters page for your project.在MongoDB Atlas UI中,转到项目的集群页面。

Warning

Navigation Improvements In Progress导航改进正在进行中

We're currently rolling out a new and improved navigation experience. If the following steps don't match your view in the Atlas UI, see the preview Atlas documentation.我们目前正在推出一种新的、改进的导航体验。如果以下步骤与Atlas UI中的视图不匹配,请参阅Atlas预览文档

  1. If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.如果尚未显示,请从导航栏的“组织”菜单中选择包含所需项目的组织。
  2. If it's not already displayed, select your project from the Projects menu in the navigation bar.如果尚未显示,请从导航栏中的“投影”菜单中选择投影。
  3. If it's not already displayed, click Clusters in the sidebar.如果尚未显示,请单击侧栏中的“集群”。

    The Clusters page displays.将显示“群集”页面。

2

Navigate to the collection.导航到集合。

  1. For the cluster that contains the sample data, click Browse Collections.对于包含示例数据的集群,单击“浏览集合”。
  2. In the left navigation pane, select the sample_training database.在左侧导航窗格中,选择sample_training数据库。
  3. Select the companies collection.选择companies集合。
3

Insert a blank document.插入空白文档。

Click the Insert Document button to display the dialog box, and then click Insert to insert a document with only the _id field.单击“插入文档”按钮以显示对话框,然后单击“插入”以插入仅包含_id字段的文档。

4

Specify a query filter document.指定查询筛选器文档。

To find a document that contains a null or missing value, specify a query filter document in the Filter field. 若要查找包含null或缺少值的文档,请在“筛选器”字段中指定查询筛选器文档A query filter document uses query operators to specify search conditions.查询筛选器文档使用查询运算符指定搜索条件。

Different query operators in MongoDB treat null values differently. To apply a query filter, copying each of the following documents into the Filter search bar and click Apply.MongoDB中的不同查询运算符对null值的处理方式不同。要应用查询筛选器,请将以下每个文档复制到“筛选器”搜索栏中,然后单击应用。

Use the following query filter to match documents that either contain a description field with a null value or do not contain the description field:使用以下查询筛选器匹配包含nulldescription字段或不包含description字段的文档:

{ description : null }

Use the following query filter to match only documents that contain a description field with a null value. 使用以下查询筛选器仅匹配包含nulldescription字段的文档。This filter specifies that the value of the field must be BSON Type此筛选器指定字段的值必须为BSON类型 Null (BSON Type 10):

{ description : { $type: 10 } }

Use the following query filter to match only documents that do not contain the description field. Only the document that you inserted earlier should appear:使用以下查询筛选器仅匹配不包含description字段的文档。只应显示您之前插入的文档:

{ description : { $exists: false } }