Database Manual / CRUD Operations

Query Documents查询文档

To query documents, specify a query predicate indicating the documents you want to return. If you specify an empty query predicate ({ }), the query returns all documents in the collection.要查询文档,请指定一个查询谓词,指示要返回的文档。如果指定空查询谓词({ }),则查询将返回集合中的所有文档。

You can query documents in MongoDB by using the following methods:您可以使用以下方法在MongoDB中查询文档:


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。


MongoDB Shell

This page provides examples of query operations using the db.collection.find() method in mongosh.本页提供了使用mongoshdb.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 query operations 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 query operations using mongoc_collection_find_with_opts.本页提供了使用mongoc_collection_find_with_opts的查询操作示例。

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实例中的test数据库,然后创建inventory集合:

C#

This page provides examples of query operations 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 query operations 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 query operations 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 query operations 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 query operations by using the MongoCollection.find() method in the MongoDB Kotlin Coroutine Driver.本页提供了使用MongoDB Kotlin协程驱动程序中的MongoCollection.find()方法进行查询操作的示例。

Tip

The driver provides com.mongodb.client.model.Filters helper methods to facilitate the creation of filter documents. 该驱动程序提供了com.mongodb.client.model.Filters辅助方法,以方便创建筛选器文档。The examples on this page use these methods to create the filter documents.本页上的示例使用这些方法创建筛选文档。

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 query operations using the motor.motor_asyncio.AsyncIOMotorCollection.find method in the Motor driver.此页面提供了使用Motor驱动程序中的motor.motor_asyncio.AsyncIOMotorCollection.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集合:

Node.js

This page provides examples of query operations using the Collection.find() method in the MongoDB Node.js Driver.本页提供了使用MongoDB Node.js驱动程序中的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集合:

PHP

This page provides examples of query operations using the MongoDB\\Collection::find() method in the MongoDB PHP Library.本页提供了使用MongoDB PHP库中的MongoDB\\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集合:

Python

This page provides examples of query operations using the pymongo.collection.Collection.find method in the PyMongo Python driver.本页提供了使用PyMongo Python驱动程序中的pymongo.collection.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集合:

Ruby

This page provides examples of query operations using the Mongo::Collection#find() method in the MongoDB Ruby Driver.本页提供了使用MongoDB Ruby驱动程序中的Mongo::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集合:

Scala

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

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

MongoDB Shell
db.inventory.insertMany([
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
]);
Compass
[
{ "item": "journal", "qty": 25, "size": { "h": 14, "w": 21, "uom": "cm" }, "status": "A" },
{ "item": "notebook", "qty": 50, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "A" },
{ "item": "paper", "qty": 100, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "D" },
{ "item": "planner", "qty": 75, "size": { "h": 22.85, "w": 30, "uom": "cm" }, "status": "D" },
{ "item": "postcard", "qty": 45, "size": { "h": 10, "w": 15.25, "uom": "cm" }, "status": "A" }
]

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 (
"item", BCON_UTF8 ("journal"),
"qty", BCON_INT64 (25),
"size", "{",
"h", BCON_DOUBLE (14),
"w", BCON_DOUBLE (21),
"uom", BCON_UTF8 ("cm"),
"}",
"status", BCON_UTF8 ("A"));

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 (
"item", BCON_UTF8 ("notebook"),
"qty", BCON_INT64 (50),
"size", "{",
"h", BCON_DOUBLE (8.5),
"w", BCON_DOUBLE (11),
"uom", BCON_UTF8 ("in"),
"}",
"status", BCON_UTF8 ("A"));

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 (
"item", BCON_UTF8 ("paper"),
"qty", BCON_INT64 (100),
"size", "{",
"h", BCON_DOUBLE (8.5),
"w", BCON_DOUBLE (11),
"uom", BCON_UTF8 ("in"),
"}",
"status", BCON_UTF8 ("D"));

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 (
"item", BCON_UTF8 ("planner"),
"qty", BCON_INT64 (75),
"size", "{",
"h", BCON_DOUBLE (22.85),
"w", BCON_DOUBLE (30),
"uom", BCON_UTF8 ("cm"),
"}",
"status", BCON_UTF8 ("D"));

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 (
"item", BCON_UTF8 ("postcard"),
"qty", BCON_INT64 (45),
"size", "{",
"h", BCON_DOUBLE (10),
"w", BCON_DOUBLE (15.25),
"uom", BCON_UTF8 ("cm"),
"}",
"status", BCON_UTF8 ("A"));

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 BsonDocument[]
{
new BsonDocument
{
{ "item", "journal" },
{ "qty", 25 },
{ "size", new BsonDocument { { "h", 14 }, { "w", 21 }, { "uom", "cm"} } },
{ "status", "A" }
},
new BsonDocument
{
{ "item", "notebook" },
{ "qty", 50 },
{ "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in"} } },
{ "status", "A" }
},
new BsonDocument
{
{ "item", "paper" },
{ "qty", 100 },
{ "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in"} } },
{ "status", "D" }
},
new BsonDocument
{
{ "item", "planner" },
{ "qty", 75 },
{ "size", new BsonDocument { { "h", 22.85 }, { "w", 30 }, { "uom", "cm"} } },
{ "status", "D" }
},
new BsonDocument
{
{ "item", "postcard" },
{ "qty", 45 },
{ "size", new BsonDocument { { "h", 10 }, { "w", 15.25 }, { "uom", "cm"} } },
{ "status", "A" }
},
};
collection.InsertMany(documents);
Go
docs := []any{
bson.D{
{"item", "journal"},
{"qty", 25},
{"size", bson.D{
{"h", 14},
{"w", 21},
{"uom", "cm"},
}},
{"status", "A"},
},
bson.D{
{"item", "notebook"},
{"qty", 50},
{"size", bson.D{
{"h", 8.5},
{"w", 11},
{"uom", "in"},
}},
{"status", "A"},
},
bson.D{
{"item", "paper"},
{"qty", 100},
{"size", bson.D{
{"h", 8.5},
{"w", 11},
{"uom", "in"},
}},
{"status", "D"},
},
bson.D{
{"item", "planner"},
{"qty", 75},
{"size", bson.D{
{"h", 22.85},
{"w", 30},
{"uom", "cm"},
}},
{"status", "D"},
},
bson.D{
{"item", "postcard"},
{"qty", 45},
{"size", bson.D{
{"h", 10},
{"w", 15.25},
{"uom", "cm"},
}},
{"status", "A"},
},
}

result, err := coll.InsertMany(context.TODO(), docs)
Java(Async)
Publisher<Success> insertManyPublisher = collection.insertMany(asList(
Document.parse("{ item: 'journal', qty: 25, size: { h: 14, w: 21, uom: 'cm' }, status: 'A' }"),
Document.parse("{ item: 'notebook', qty: 50, size: { h: 8.5, w: 11, uom: 'in' }, status: 'A' }"),
Document.parse("{ item: 'paper', qty: 100, size: { h: 8.5, w: 11, uom: 'in' }, status: 'D' }"),
Document.parse("{ item: 'planner', qty: 75, size: { h: 22.85, w: 30, uom: 'cm' }, status: 'D' }"),
Document.parse("{ item: 'postcard', qty: 45, size: { h: 10, w: 15.25, uom: 'cm' }, status: 'A' }")
));
Java(Sync)
collection.insertMany(asList(
Document.parse("{ item: 'journal', qty: 25, size: { h: 14, w: 21, uom: 'cm' }, status: 'A' }"),
Document.parse("{ item: 'notebook', qty: 50, size: { h: 8.5, w: 11, uom: 'in' }, status: 'A' }"),
Document.parse("{ item: 'paper', qty: 100, size: { h: 8.5, w: 11, uom: 'in' }, status: 'D' }"),
Document.parse("{ item: 'planner', qty: 75, size: { h: 22.85, w: 30, uom: 'cm' }, status: 'D' }"),
Document.parse("{ item: 'postcard', qty: 45, size: { h: 10, w: 15.25, uom: 'cm' }, status: 'A' }")
));
Kotlin(Coroutine)
collection.insertMany(
listOf(
Document("item", "journal")
.append("qty", 25)
.append("size", Document("h", 14)
.append("w", 21)
.append("uom", "cm")
)
.append("status", "A"),
Document("item", "notebook")
.append("qty", 50)
.append("size", Document("h", 8.5)
.append("w", 11)
.append("uom", "in")
)
.append("status", "A"),
Document("item", "paper")
.append("qty", 100)
.append("size", Document("h", 8.5)
.append("w", 11)
.append("uom", "in")
)
.append("status", "D"),
Document("item", "planner")
.append("qty", 75)
.append("size", Document("h", 22.85)
.append("w", 30)
.append("uom", "cm")
)
.append("status", "D"),
Document("item", "postcard")
.append("qty", 45)
.append("size", Document("h", 10)
.append("w", 15.25)
.append("uom", "cm")
)
.append("status", "A"),
)
)
Motor
await db.inventory.insert_many(
[
{
"item": "journal",
"qty": 25,
"size": {"h": 14, "w": 21, "uom": "cm"},
"status": "A",
},
{
"item": "notebook",
"qty": 50,
"size": {"h": 8.5, "w": 11, "uom": "in"},
"status": "A",
},
{
"item": "paper",
"qty": 100,
"size": {"h": 8.5, "w": 11, "uom": "in"},
"status": "D",
},
{
"item": "planner",
"qty": 75,
"size": {"h": 22.85, "w": 30, "uom": "cm"},
"status": "D",
},
{
"item": "postcard",
"qty": 45,
"size": {"h": 10, "w": 15.25, "uom": "cm"},
"status": "A",
},
]
)
Node.js
await db.collection('inventory').insertMany([
{
item: 'journal',
qty: 25,
size: { h: 14, w: 21, uom: 'cm' },
status: 'A'
},
{
item: 'notebook',
qty: 50,
size: { h: 8.5, w: 11, uom: 'in' },
status: 'A'
},
{
item: 'paper',
qty: 100,
size: { h: 8.5, w: 11, uom: 'in' },
status: 'D'
},
{
item: 'planner',
qty: 75,
size: { h: 22.85, w: 30, uom: 'cm' },
status: 'D'
},
{
item: 'postcard',
qty: 45,
size: { h: 10, w: 15.25, uom: 'cm' },
status: 'A'
}
]);
PHP
$insertManyResult = $db->inventory->insertMany([
[
'item' => 'journal',
'qty' => 25,
'size' => ['h' => 14, 'w' => 21, 'uom' => 'cm'],
'status' => 'A',
],
[
'item' => 'notebook',
'qty' => 50,
'size' => ['h' => 8.5, 'w' => 11, 'uom' => 'in'],
'status' => 'A',
],
[
'item' => 'paper',
'qty' => 100,
'size' => ['h' => 8.5, 'w' => 11, 'uom' => 'in'],
'status' => 'D',
],
[
'item' => 'planner',
'qty' => 75,
'size' => ['h' => 22.85, 'w' => 30, 'uom' => 'cm'],
'status' => 'D',
],
[
'item' => 'postcard',
'qty' => 45,
'size' => ['h' => 10, 'w' => 15.25, 'uom' => 'cm'],
'status' => 'A',
],
]);
Python
db.inventory.insert_many(
[
{
"item": "journal",
"qty": 25,
"size": {"h": 14, "w": 21, "uom": "cm"},
"status": "A",
},
{
"item": "notebook",
"qty": 50,
"size": {"h": 8.5, "w": 11, "uom": "in"},
"status": "A",
},
{
"item": "paper",
"qty": 100,
"size": {"h": 8.5, "w": 11, "uom": "in"},
"status": "D",
},
{
"item": "planner",
"qty": 75,
"size": {"h": 22.85, "w": 30, "uom": "cm"},
"status": "D",
},
{
"item": "postcard",
"qty": 45,
"size": {"h": 10, "w": 15.25, "uom": "cm"},
"status": "A",
},
]
)
Ruby
client[:inventory].insert_many([{ item: 'journal',
qty: 25,
size: { h: 14, w: 21, uom: 'cm' },
status: 'A' },
{ item: 'notebook',
qty: 50,
size: { h: 8.5, w: 11, uom: 'in' },
status: 'A' },
{ item: 'paper',
qty: 100,
size: { h: 8.5, w: 11, uom: 'in' },
status: 'D' },
{ item: 'planner',
qty: 75,
size: { h: 22.85, w: 30, uom: 'cm' },
status: 'D' },
{ item: 'postcard',
qty: 45,
size: { h: 10, w: 15.25, uom: 'cm' },
status: 'A' }
])
Scala
collection.insertMany(Seq(
Document("""{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" }"""),
Document("""{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" }"""),
Document("""{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" }"""),
Document("""{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" }"""),
Document("""{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }""")
)).execute()

Select All Documents in a Collection选择集合中的所有文档

MongoDB Shell

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. The query filter parameter determines the select criteria:要选择集合中的所有文档,请将一个空文档作为查询筛选器参数传递给find方法。查询筛选器参数确定选择条件:

Compass

To select all documents in the collection, pass an empty document as the query filter parameter to the query bar. 要选择集合中的所有文档,请将一个空文档作为查询筛选器参数传递给查询栏The query filter parameter determines the select criteria:查询筛选器参数确定选择条件:

C

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. The query filter parameter determines the select criteria:要选择集合中的所有文档,请将一个空文档作为查询筛选器参数传递给find方法。查询筛选器参数确定选择条件:

C#

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. The query filter parameter determines the select criteria:要选择集合中的所有文档,请将一个空文档作为查询筛选器参数传递给find方法。查询筛选器参数确定选择条件:

Go

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. The query filter parameter determines the select criteria:要选择集合中的所有文档,请将一个空文档作为查询筛选器参数传递给find方法。查询筛选器参数确定选择条件:

Java(Async)

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. The query filter parameter determines the select criteria:要选择集合中的所有文档,请将一个空文档作为查询筛选器参数传递给find方法。查询筛选器参数确定选择条件:

Java(Sync)

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. The query filter parameter determines the select criteria:要选择集合中的所有文档,请将一个空文档作为查询筛选器参数传递给find方法。查询筛选器参数确定选择条件:

Kotlin(Coroutine)

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. The query filter parameter determines the select criteria:要选择集合中的所有文档,请将一个空文档作为查询筛选器参数传递给find方法。查询筛选器参数确定选择条件:

Motor

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. The query filter parameter determines the select criteria:要选择集合中的所有文档,请将一个空文档作为查询筛选器参数传递给find方法。查询筛选器参数确定选择条件:

Node.js

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. The query filter parameter determines the select criteria:要选择集合中的所有文档,请将一个空文档作为查询筛选器参数传递给find方法。查询筛选器参数确定选择条件:

PHP

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. The query filter parameter determines the select criteria:要选择集合中的所有文档,请将一个空文档作为查询筛选器参数传递给find方法。查询筛选器参数确定选择条件:

Python

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. The query filter parameter determines the select criteria:要选择集合中的所有文档,请将一个空文档作为查询筛选器参数传递给find方法。查询筛选器参数确定选择条件:

Ruby

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. The query filter parameter determines the select criteria:要选择集合中的所有文档,请将一个空文档作为查询筛选器参数传递给find方法。查询筛选器参数确定选择条件:

Scala

To select all documents in the collection, pass an empty document as the query filter parameter to the find method. The query filter parameter determines the select criteria:要选择集合中的所有文档,请将一个空文档作为查询筛选器参数传递给find方法。查询筛选器参数确定选择条件:

MongoDB Shell
db.inventory.find( {} )
Compass
Compass select all documents in collection
C
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;

collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW (NULL);
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.Empty;
var result = collection.Find(filter).ToList();
Go
cursor, err := coll.Find(
context.TODO(),
bson.D{},
)
Java(Async)
FindPublisher<Document> findPublisher = collection.find(new Document());
Java(Sync)
FindIterable<Document> findIterable = collection.find(new Document());
Kotlin(Coroutine)
val flowInsertMany = collection
.find(empty())
Motor
cursor = db.inventory.find({})
Node.js
const cursor = db.collection('inventory').find({});
PHP
$cursor = $db->inventory->find([]);
Python
cursor = db.inventory.find({})
Ruby
client[:inventory].find({})
Scala
var findObservable = collection.find(Document())

This operation uses a query predicate of {}, which corresponds to the following SQL statement:此操作使用查询谓词{},它对应于以下SQL语句:

SELECT * FROM inventory
MongoDB Shell

For more information on the syntax of the method, see find().有关该方法语法的更多信息,请参阅find()

Compass

For more information on the MongoDB Compass query bar, see Query Bar.有关MongoDB Compass查询栏的更多信息,请参阅查询栏

C

For more information on the syntax of the method, see mongoc_collection_find_with_opts.有关该方法语法的更多信息,请参阅mongoc_collection_find_with_opts

C#

For more information on the syntax of the method, see Find().有关该方法语法的更多信息,请参阅Find()

Java(Async)

For more information on the syntax of the method, see com.mongodb.reactivestreams.client.MongoCollection.find.有关该方法语法的更多信息,请参阅com.mongodb.reactivestreams.client.MongoCollection.find

Java(Sync)

For more information on the syntax of the method, see com.mongodb.client.MongoCollection.find.

Kotlin(Coroutine)

For more information on the syntax of the method, see MongoCollection.find().有关该方法语法的更多信息,请参阅MongoCollection.find()

Node.js

To see supported options for the find() method, see find().要查看find()方法的支持选项,请参阅find()

PHP

For more information on the syntax of the method, see find().有关该方法语法的更多信息,请参阅find()

Python

For more information on the syntax of the method, see find.有关该方法语法的更多信息,请参阅find

Ruby

For more information on the syntax of the method, see find().有关该方法语法的更多信息,请参阅find()

Scala

For more information on the syntax of the method, see collection.find().有关该方法语法的更多信息,请参阅collection.find()

Specify Equality Condition指定平等条件

MongoDB Shell

To specify equality conditions, use <field>:<value> expressions in the query filter document:要指定相等条件,请在查询筛选器文档中使用<field>:<value>表达式:

{ <field1>: <value1>, ... }
Compass

To specify equality conditions, use <field>:<value> expressions in the query filter document:要指定相等条件,请在查询筛选器文档中使用<field>:<value>表达式:

{ <field1>: <value1>, ... }
C

To specify equality conditions, use <field>:<value> expressions in the query filter document:要指定相等条件,请在查询筛选器文档中使用<field>:<value>表达式:

{ <field1>: <value1>, ... }
C#

To specify equality conditions, construct a filter using the Eq method:要指定相等条件,请使用Eq方法构造一个筛选器:

Builders<BsonDocument>.Filter.Eq(<field>, <value>);
Java(Async)

To specify equality conditions, use the com.mongodb.client.model.Filters.eq method to create the query filter document:要指定相等条件,请使用com.mongodb.client.model.Filters.eq方法创建查询筛选器文档

and(eq(<field1>, <value1>), eq(<field2>, <value2>) ...)
Java(Sync)

To specify equality conditions, use the com.mongodb.client.model.Filters.eq_ method to create the query filter document:要指定相等条件,请使用com.mongodb.client.model.Filters.eq_方法创建查询筛选器文档

and(eq(<field1>, <value1>), eq(<field2>, <value2>) ...)
Kotlin(Coroutine)

To specify equality conditions, use the Filters.eq() method to create the query filter document:要指定相等条件,请使用Filters.eq()方法创建查询筛选器文档

and(eq(<field1>, <value1>), eq(<field2>, <value2>) ...)
Motor

To specify equality conditions, use <field>:<value> expressions in the query filter document:要指定相等条件,请在查询筛选器文档中使用<field>:<value>表达式:

{ <field1>: <value1>, ... }
Node.js

To specify equality conditions, use <field>:<value> expressions in the query filter document:要指定相等条件,请在查询筛选器文档中使用<field>:<value>表达式:

{ <field1>: <value1>, ... }
PHP

To specify equality conditions, use <field> => <value> expressions in the query filter document:要指定相等条件,请在查询筛选器文档中使用<field> => <value>表达式:

[ <field1> => <value1>, ... ]
Python

To specify equality conditions, use <field>:<value> expressions in the query filter document:要指定相等条件,请在查询筛选器文档中使用<field>:<value>表达式:

{ <field1>: <value1>, ... }
Ruby

To specify equality conditions, use <field> => <value> expressions in the query filter document:要指定相等条件,请在查询筛选器文档中使用<field> => <value>表达式:

{ <field1> => <value1>, ... }
Scala

To specify equality conditions, use the com.mongodb.client.model.Filters.eq_ method to create the query filter document:要指定相等条件,请使用com.mongodb.client.model.Filters.eq_方法创建查询筛选器文档

and(equal(<field1>, <value1>), equal(<field2>, <value2>) ...)

The following example selects from the inventory collection all documents where the status equals "D":以下示例从inventory集合中选择status"D"的所有文档:

MongoDB Shell
db.inventory.find( { status: "D" } )
Compass

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

{ status: "D" }
C
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;

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

This operation uses a query predicate of { status: "D" }, which corresponds to the following SQL statement:此操作使用{ status: "D" }的查询谓词,它对应于以下SQL语句:

SELECT * FROM inventory WHERE status = "D"
Compass

Note

The MongoDB Compass query bar autocompletes the current query based on the keys in your collection's documents, including keys in embedded sub-documents.MongoDB Compass查询栏会根据集合文档中的键(包括嵌入子文档中的键值)自动完成当前查询。

Specify Conditions Using Query Operators使用查询运算符指定条件

MongoDB Shell

A query filter document can use the query operators to specify conditions in the following form:查询筛选文档可以使用查询运算符以以下形式指定条件:

{ <field1>: { <operator1>: <value1> }, ... }
Compass

A query filter document can use the query operators to specify conditions in the following form:查询筛选文档可以使用查询运算符以以下形式指定条件:

{ <field1>: { <operator1>: <value1> }, ... }
C

A query filter document can use the query operators to specify conditions in the following form:查询筛选文档可以使用查询运算符以以下形式指定条件:

{ <field1>: { <operator1>: <value1> }, ... }
C#

In addition to the equality filter, MongoDB provides various query operators to specify filter conditions. 除了等式筛选器外,MongoDB还提供了各种查询运算符来指定筛选条件。Use the FilterDefinitionBuilder methods to create a filter document. For example:使用FilterDefinitionBuilder方法创建筛选器文档。例如:

var builder = Builders<BsonDocument>.Filter;
builder.And(builder.Eq(<field1>, <value1>), builder.Lt(<field2>, <value2>));
Go

In addition to the equality filter, MongoDB provides various query operators to specify filter conditions. 除了等式筛选器外,MongoDB还提供了各种查询运算符来指定筛选条件。Use the bson package to create query operators for filter documents. For example:使用bson包为筛选文档创建查询运算符。例如:

filter := bson.D{
{"$and", bson.A{
bson.D{{"field1", bson.D{{"$eq", value1}}}},
bson.D{{"field2", bson.D{{"$lt", value2}}}},
}},
}
Java(Async)

In addition to the equality condition, MongoDB provides various query operators to specify filter conditions. 除了相等条件外,MongoDB还提供了各种查询运算符来指定筛选条件。Use the com.mongodb.client.model.Filters helper methods to facilitate the creation of filter documents. For example:使用com.mongodb.client.model.Filters辅助方法来简化筛选器文档的创建。例如:

and(gte(<field1>, <value1>), lt(<field2>, <value2>), eq(<field3>, <value3>))
Java(Sync)

In addition to the equality condition, MongoDB provides various query operators to specify filter conditions. 除了相等条件外,MongoDB还提供了各种查询运算符来指定筛选条件。Use the com.mongodb.client.model.Filters helper methods to facilitate the creation of filter documents. For example:使用com.mongodb.client.model.Filters辅助方法来简化筛选器文档的创建。例如:

and(gte(<field1>, <value1>), lt(<field2>, <value2>), eq(<field3>, <value3>))
Kotlin(Coroutine)

In addition to the equality condition, MongoDB provides various query operators to specify filter conditions. Use the com.mongodb.client.model.Filters helper methods to facilitate the creation of filter documents. For example:

and(gte(<field1>, <value1>), lt(<field2>, <value2>), eq(<field3>, <value3>))
Motor

A query filter document can use the query operators to specify conditions in the following form:查询筛选文档可以使用查询运算符以以下形式指定条件:

{ <field1>: { <operator1>: <value1> }, ... }
Node.js

A query filter document can use the query operators to specify conditions in the following form:查询筛选文档可以使用查询运算符以以下形式指定条件:

{ <field1>: { <operator1>: <value1> }, ... }
PHP

A query filter document can use the query operators to specify conditions in the following form:查询筛选文档可以使用查询运算符以以下形式指定条件:

[ <field1> => [ <operator1> => <value1> ], ... ]
Python

A query filter document can use the query operators to specify conditions in the following form:查询筛选文档可以使用查询运算符以以下形式指定条件:

{ <field1>: { <operator1>: <value1> }, ... }
Ruby

A query filter document can use the query operators to specify conditions in the following form:查询筛选文档可以使用查询运算符以以下形式指定条件:

{ <field1> => { <operator1> => <value1> }, ... }
Scala

In addition to the equality condition, MongoDB provides various query operators to specify filter conditions. 除了相等条件外,MongoDB还提供了各种查询运算符来指定筛选条件。Use the com.mongodb.client.model.Filters_ helper methods to facilitate the creation of filter documents. For example:使用com.mongodb.client.model.Filters_助手方法来简化筛选器文档的创建。例如:

and(gte(<field1>, <value1>), lt(<field2>, <value2>), equal(<field3>, <value3>))

The following example retrieves all documents from the inventory collection where status equals either "A" or "D":以下示例从status"A""D"inventory集合中检索所有文档:

MongoDB Shell
db.inventory.find( { status: { $in: [ "A", "D" ] } } )
Compass

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

{ status: { $in: [ "A", "D" ] } }
C
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;

collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW (
"status", "{",
"$in", "[",
BCON_UTF8 ("A"), BCON_UTF8 ("D"),
"]",
"}");
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);
C#
var filter = Builders<BsonDocument>.Filter.In("status", new[] { "A", "D" });
var result = collection.Find(filter).ToList();
Go
cursor, err := coll.Find(
context.TODO(),
bson.D{{"status", bson.D{{"$in", bson.A{"A", "D"}}}}})
Java(Async)
findPublisher = collection.find(in("status", "A", "D"));
Java(Sync)
findIterable = collection.find(in("status", "A", "D"));
Kotlin(Coroutine)
val findFlow = collection
.find(`in`("status", "A", "D"))
Motor
cursor = db.inventory.find({"status": {"$in": ["A", "D"]}})
Node.js
const cursor = db.collection('inventory').find({
status: { $in: ['A', 'D'] }
});
PHP
$cursor = $db->inventory->find(['status' => ['$in' => ['A', 'D']]]);
Python
cursor = db.inventory.find({"status": {"$in": ["A", "D"]}})
Ruby
client[:inventory].find(status: { '$in' => [ 'A', 'D' ]})
Scala
findObservable = collection.find(in("status", "A", "D"))

Note

Although you can express this query using the $or operator, use the $in operator rather than the $or operator when performing equality checks on the same field.虽然可以使用$or运算符表示此查询,但在对同一字段执行相等性检查时,请使用$in运算符而不是$or运算符。

The operation uses a query predicate of { status: { $in: [ "A", "D" ] } }, which corresponds to the following SQL statement:该操作使用查询谓词{ status: { $in: [ "A", "D" ] } },它对应于以下SQL语句:

SELECT * FROM inventory WHERE status in ("A", "D")

For the complete list of MongoDB query operators, see Query Predicates.有关MongoDB查询运算符的完整列表,请参阅查询谓词

Specify AND Conditions指定AND条件

A compound query can specify conditions for more than one field in the collection's documents. Implicitly, a logical AND conjunction connects the clauses of a compound query so that the query selects the documents in the collection that match all the conditions.复合查询可以为集合文档中的多个字段指定条件。隐含地,逻辑AND连接复合查询的子句,以便查询选择集合中符合所有条件的文档。

The following example retrieves all documents in the inventory collection where the status equals "A" and qty is less than ($lt) 30:以下示例检索status"A"qty小于($lt30inventory集合中的所有文档:

MongoDB Shell
db.inventory.find( { status: "A", qty: { $lt: 30 } } )
Compass

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

{ status: "A", qty: { $lt: 30 } }
C
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;

collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW (
"status", BCON_UTF8 ("A"),
"qty", "{",
"$lt", BCON_INT64 (30),
"}");
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);
C#
var builder = Builders<BsonDocument>.Filter;
var filter = builder.And(builder.Eq("status", "A"), builder.Lt("qty", 30));
var result = collection.Find(filter).ToList();
Go
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"status", "A"},
{"qty", bson.D{{"$lt", 30}}},
})
Java(Async)
findPublisher = collection.find(and(eq("status", "A"), lt("qty", 30)));
Java(Sync)
findIterable = collection.find(and(eq("status", "A"), lt("qty", 30)));
Kotlin(Coroutine)
val findFlow = collection
.find(and(eq("status", "A"), lt("qty", 30)))
Motor
cursor = db.inventory.find({"status": "A", "qty": {"$lt": 30}})
Node.js
const cursor = db.collection('inventory').find({
status: 'A',
qty: { $lt: 30 }
});
PHP
$cursor = $db->inventory->find([
'status' => 'A',
'qty' => ['$lt' => 30],
]);
Python
cursor = db.inventory.find({"status": "A", "qty": {"$lt": 30}})
Ruby
client[:inventory].find(status: 'A', qty: { '$lt' => 30 })
Scala
findObservable = collection.find(and(equal("status", "A"), lt("qty", 30)))

The operation uses a query predicate of { status: "A", qty: { $lt: 30 } }, which corresponds to the following SQL statement:该操作使用{ status: "A", qty: { $lt: 30 } }的查询谓词,它对应于以下SQL语句:

SELECT * FROM inventory WHERE status = "A" AND qty < 30

See comparison operators for other MongoDB comparison operators.其他MongoDB比较运算符请参见比较运算符

Specify OR Conditions指定OR条件

Using the $or operator, you can specify a compound query that joins each clause with a logical OR conjunction so that the query selects the documents in the collection that match at least one condition.使用$or运算符,您可以指定一个复合查询,该查询将每个子句与逻辑or连接起来,以便查询选择集合中至少符合一个条件的文档。

The following example retrieves all documents in the collection where the status equals "A" or qty is less than ($lt) 30:以下示例检索集合中status等于"A"qty小于($lt30的所有文档:

MongoDB Shell
db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )
Compass

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

{ $or: [ { status: "A" }, { qty: { $lt: 30 } } ] }
C
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;

collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW (
"$or", "[",
"{",
"status", BCON_UTF8 ("A"),
"}","{",
"qty", "{",
"$lt", BCON_INT64 (30),
"}",
"}",
"]");
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);
C#
var builder = Builders<BsonDocument>.Filter;
var filter = builder.Or(builder.Eq("status", "A"), builder.Lt("qty", 30));
var result = collection.Find(filter).ToList();
Go
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"$or",
bson.A{
bson.D{{"status", "A"}},
bson.D{{"qty", bson.D{{"$lt", 30}}}},
}},
})
Java(Async)
findPublisher = collection.find(or(eq("status", "A"), lt("qty", 30)));
Java(Sync)
findIterable = collection.find(or(eq("status", "A"), lt("qty", 30)));
Kotlin(Coroutine)
val findFlow = collection
.find(or(eq("status", "A"), lt("qty", 30)))
Motor
cursor = db.inventory.find({"$or": [{"status": "A"}, {"qty": {"$lt": 30}}]})
Node.js
const cursor = db.collection('inventory').find({
$or: [{ status: 'A' }, { qty: { $lt: 30 } }]
});
PHP
$cursor = $db->inventory->find([
'$or' => [
['status' => 'A'],
['qty' => ['$lt' => 30]],
],
]);
Python
cursor = db.inventory.find({"$or": [{"status": "A"}, {"qty": {"$lt": 30}}]})
Ruby
client[:inventory].find('$or' => [{ status: 'A' },
{ qty: { '$lt' => 30 } }
])
Scala
findObservable = collection.find(or(equal("status", "A"), lt("qty", 30)))

The operation uses a query predicate of { $or: [ { status: 'A' }, { qty: { $lt: 30 } } ] }, which corresponds to the following SQL statement:该操作使用查询谓词{ $or: [ { status: 'A' }, { qty: { $lt: 30 } } ] },它对应于以下SQL语句:

SELECT * FROM inventory WHERE status = "A" OR qty < 30

Note

Queries that use comparison operators are subject to Type Bracketing.使用比较运算符的查询受类型括号的约束。

Specify AND as well as OR Conditions指定ANDOR条件

In the following example, the compound query document selects all documents in the collection where the status equals "A" and either qty is less than ($lt) 30 or item starts with the character p:在以下示例中,复合查询文档选择集合中status等于"A"qty小于($lt30item以字符p开头的所有文档:

MongoDB Shell
db.inventory.find( {
status: "A",
$or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]
} )
Compass

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

{ status: "A", $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ] }
C
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;

collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW (
"status", BCON_UTF8 ("A"),
"$or", "[",
"{",
"qty", "{",
"$lt", BCON_INT64 (30),
"}",
"}","{",
"item", BCON_REGEX ("^p", ""),
"}",
"]");
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);
C#
var builder = Builders<BsonDocument>.Filter;
var filter = builder.And(
builder.Eq("status", "A"),
builder.Or(builder.Lt("qty", 30), builder.Regex("item", new BsonRegularExpression("^p"))));
var result = collection.Find(filter).ToList();
Go
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"status", "A"},
{"$or", bson.A{
bson.D{{"qty", bson.D{{"$lt", 30}}}},
bson.D{{"item", bson.Regex{Pattern: "^p", Options: ""}}},
}},
})
Java(Async)
findPublisher = collection.find(
and(eq("status", "A"),
or(lt("qty", 30), regex("item", "^p")))
);
Java(Sync)
findIterable = collection.find(
and(eq("status", "A"),
or(lt("qty", 30), regex("item", "^p")))
);
Kotlin(Coroutine)
val findFlow = collection
.find(
and(eq("status", "A"),
or(lt("qty", 30), regex("item", "^p")))
)
Motor
cursor = db.inventory.find(
{"status": "A", "$or": [{"qty": {"$lt": 30}}, {"item": {"$regex": "^p"}}]}
)
Node.js
const cursor = db.collection('inventory').find({
status: 'A',
$or: [{ qty: { $lt: 30 } }, { item: { $regex: '^p' } }]
});
PHP
$cursor = $db->inventory->find([
'status' => 'A',
'$or' => [
['qty' => ['$lt' => 30]],
// Alternatively: ['item' => new \MongoDB\BSON\Regex('^p')]
['item' => ['$regex' => '^p']],
],
]);
Python
cursor = db.inventory.find(
{"status": "A", "$or": [{"qty": {"$lt": 30}}, {"item": {"$regex": "^p"}}]}
)
Ruby
client[:inventory].find(status: 'A',
'$or' => [{ qty: { '$lt' => 30 } },
{ item: { '$regex' => BSON::Regexp::Raw.new('^p') } }
])
Scala
findObservable = collection.find(and(
equal("status", "A"),
or(lt("qty", 30), regex("item", "^p")))
)

The operation uses a query predicate of:该操作使用以下查询谓词:

{
status: 'A',
$or: [
{ qty: { $lt: 30 } }, { item: { $regex: '^p' } }
]
}

which corresponds to the following SQL statement:其对应于以下SQL语句:

SELECT * FROM inventory WHERE status = "A" AND ( qty < 30 OR item LIKE "p%")

Note

MongoDB supports regular expressions $regex queries to perform string pattern matches.MongoDB支持正则表达式$regex查询来执行字符串模式匹配。

Query Documents with MongoDB Atlas使用MongoDB Atlas查询文档

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

To project fields to return from a query in MongoDB Atlas, follow these steps:要在MongoDB Atlas中投影要从查询返回的字段,请执行以下步骤:

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_mflix database.在左侧导航窗格中,选择sample_mflix数据库。
  3. Select the movies collection.选择movies集合。
3

Specify the Filter field指定筛选器字段

Specify the query filter document in the Filter field. A query filter document uses query operators to specify search conditions.在“筛选器”字段中指定查询筛选器文档。查询筛选器文档使用查询运算符指定搜索条件。

Copy the following query filter document into the Filter search bar:将以下查询筛选器文档复制到“筛选器”搜索栏中:

{ year: 1924 }
4

Click Apply单击“应用”

This query filter returns all documents in the sample_mflix.movies collection where the year field matches 1924.此查询筛选器返回sample_mflix.movies集合中year字段与1924匹配的所有文档。

Additional Query Tutorials其他查询教程

For additional query examples, see:有关其他查询示例,请参阅:

Behavior行为

Cursor游标

MongoDB Shell

The db.collection.find() method returns a cursor to the matching documents.db.collection.find()方法将游标返回到匹配的文档。

Compass

The MongoDB Compass Find operation opens a cursor to the matching documents of the collection based on the find query.MongoDB Compass“查找”操作根据查找查询打开一个指向集合中匹配文档的游标

For more information on sampling in MongoDB Compass, see the Compass FAQ.有关MongoDB Compass中采样的更多信息,请参阅Compass常见问题解答

C

The mongoc_collection_find_with_opts method returns a cursor to the matching documents.mongoc_collection_find_with_opts方法将游标返回到匹配的文档。

C#

The MongoCollection.Find() method returns a cursor to the matching documents. MongoCollection.Find()方法将游标返回到匹配的文档。See the MongoDB C# driver documentation for iterating over a cursor.有关迭代游标的信息,请参阅MongoDB C#驱动程序文档。

Go

The Collection.Find function returns a Cursor to the matching documents. Collection.Find函数将游标返回给匹配的文档。See the Cursor documentation for more information.有关更多信息,请参阅Cursor文档。

Java(Async)

com.mongodb.reactivestreams.client.MongoCollection.find returns an instance of the com.mongodb.reactivestreams.client.FindPublisher interface.返回com.mongodb.reactivestreams.client.FindPublisher接口的实例。

Java(Sync)

The com.mongodb.client.MongoCollection.find method returns an instance of the com.mongodb.client.FindIterable interface.com.mongodb.client.MongoCollection.find方法返回com.mongodb.client.FindIterable接口的实例。

Kotlin(Coroutine)

The MongoCollection.find() method returns an instance of the FindFlow class.MongoCollection.find()方法返回FindFlow类的一个实例。

Node.js

The Collection.find() method returns a cursor.Collection.find()方法返回一个游标

PHP

The MongoDB\\Collection::find() method returns a cursor to the matching documents. MongoDB\\Collection::find()方法将游标返回到匹配的文档。See the MongoDB PHP Library documentation for iterating over a cursor.有关迭代游标的信息,请参阅MongoDB PHP库文档。

Python

The pymongo.collection.Collection.find method returns a cursor to the matching documents. pymongo.collection.Collection.find方法将游标返回到匹配的文档。See the PyMongo documentation for iterating over a cursor.有关迭代游标的信息,请参阅PyMongo文档。

Ruby

The Mongo::Collection#find() method returns a CollectionView, which is an Enumerable. Mongo::Collection#find()方法返回一个CollectionView,它是一个EnumerableA Cursor is created when the View is enumerated; for example, by calling #to_a() or #each(). 枚举View时创建游标;例如,通过调用#to_a()#each()You can also get an Enumerator by calling #to_enum() on the View. 您还可以通过在View上调用#to_enum()来获取Enumerator(枚举器)。See the Ruby driver API documentation for iterating over a cursor.请参阅Ruby驱动程序API文档,了解在游标上的迭代

Scala

The collection.find() method returns the find Observable.collection.find()方法返回find Observable

Concurrent Updates While Using a Cursor使用游标时的并发更新

As a cursor returns documents, other operations may run in the background and affect the results, depending on the read concern level. For details, see Read Isolation, Consistency, and Recency.当游标返回文档时,其他操作可能会在后台运行并影响结果,具体取决于读取关注级别。有关详细信息,请参阅读取隔离、一致性和最近性

Read Isolation读取隔离

For reads to Replica sets and replica set shards, read concern allows clients to choose a level of isolation for their reads. 对于对副本集和副本集分片的读取,读取关注允许客户端为其读取选择隔离级别。For more information, see Read Concern.有关更多信息,请参阅读取关注

Query Result Format查询结果格式

When you run a find operation with a MongoDB driver or mongosh, the command returns a cursor that manages query results. The query results are not returned as an array of documents.当您使用MongoDB驱动程序或mongosh运行查找操作时,该命令会返回一个管理查询结果的游标。查询结果不会以文档数组的形式返回。

To learn how to iterate through documents in a cursor, refer to your driver's documentation. If you are using mongosh, see Iterate a Cursor in mongosh.要了解如何在游标中迭代文档,请参阅驱动程序文档。如果您正在使用mongosh,请参阅mongosh中迭代游标

Additional Methods and Options其他方法和选项

MongoDB Shell

The following can also read documents from a collection:以下人员也可以从集合中读取文档:

Note

The db.collection.findOne() method performs the same operation as the db.collection.find() method with a limit of 1.db.collection.findOne()方法执行与db.collection.find()方法相同的操作,只是limit1

Compass

In addition to filter, MongoDB Compass also allows you to pass the following options to the query bar:除了filter,MongoDB Compass还允许您将以下选项传递给查询栏:

ProjectSpecify which fields to return in the resulting data.指定在结果数据中返回哪些字段。
SortSpecify the sort order of the returned documents.指定返回文档的排序顺序。
SkipSpecify the first n-number of document to skip before returning the result set.在返回结果集之前,指定要跳过的第一个n个文档。
LimitSpecify the maximum number of documents to return.指定要返回的最大文档数。
C

The following method can also read documents from a collection:以下方法也可以从集合中读取文档:

C#

The following can also read documents from a collection:以下人员也可以从集合中读取文档:

Note

The MongoCollection.FindOne() method performs the same operation as the MongoCollection.Find() method with a limit of 1.MongoCollection.FindOne()方法执行与MongoCollection.Find()方法相同的操作,只是limit1

Go

The following can also read documents from a collection:以下人员也可以从集合中读取文档:

Java(Sync)

The following can also read documents from a collection:以下人员也可以从集合中读取文档:

Kotlin(Coroutine)

The following methods can also read documents from a collection:以下方法也可以从集合中读取文档:

Node.js

The following can also read documents from a collection:以下人员也可以从集合中读取文档:

Note

The Collection.findOne() method performs the same operation as the Collection.find() method with a limit of 1.Collection.findOne()方法执行与Collection.find()方法相同的操作,只是limit1

PHP

The following can also read documents from a collection:以下人员也可以从集合中读取文档:

Note

The MongoDB\\Collection::findOne() method performs the same operation as the MongoDB\\Collection::find() method with a limit of 1.MongoDB\\Collection::findOne()方法执行与MongoDB\\Collection::find()方法相同的操作,只是limit1

Python

The following can also read documents from a collection:以下人员也可以从集合中读取文档:

Note

The pymongo.collection.Collection.find_one method performs the same operation as the the pymongo.collection.Collection.find method with a limit of 1.pymongo.collection.Collection.find_one方法执行与pymongo.collection.Collection.find方法相同的操作,只是limit1

Ruby

The following can also read documents from a collection:以下人员也可以从集合中读取文档:

Scala

The following can also read documents from a collection:以下人员也可以从集合中读取文档: