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中查询文档:
Your programming language's driver.你的编程语言的驱动程序。The MongoDB Atlas UI. To learn more, see Query Documents with MongoDB Atlas.MongoDB Atlas用户界面。要了解更多信息,请参阅使用MongoDB Atlas查询文档。- MongoDB Compass
.。
➤ 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。
This page provides examples of query operations 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集合:
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集合:
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集合:
This page provides examples of query operations using the MongoCollection.Find() method in the MongoDB C# Driver.
The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:
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:
This page provides examples of query operations 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. Connect to a test database in your MongoDB instance then create the inventory collection:
This page provides examples of query operations 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. Connect to a test database in your MongoDB instance then create the inventory collection:
This page provides examples of query operations by using the MongoCollection.find() method in the MongoDB Kotlin Coroutine 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. Connect to a test database in your MongoDB instance then create the inventory collection:
This page provides examples of query operations using the motor.motor_asyncio.AsyncIOMotorCollection.find method in the Motor driver.
The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:
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:
This page provides examples of query operations using the MongoDB\\Collection::find() method in the MongoDB PHP Library.
The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:
This page provides examples of query operations using the pymongo.collection.Collection.find method in the PyMongo Python driver.
The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:
This page provides examples of query operations using the Mongo::Collection#find() method in the MongoDB Ruby Driver.
The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:
This page provides examples of query operations using the collection.find() method in the MongoDB Scala Driver.
The examples on this page use the inventory collection. Connect to a test database in your MongoDB instance then create the inventory collection:
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" }
]);[
{ "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.
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);
}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);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)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' }")
));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' }")
));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"),
)
)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",
},
]
)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'
}
]);$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',
],
]);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",
},
]
)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' }
])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选择集合中的所有文档
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方法。查询筛选器参数确定选择条件:
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:查询筛选器参数确定选择条件:
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:
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:
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:
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:
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:
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:
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:
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方法。查询筛选器参数确定选择条件:
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:
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:
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:
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:
db.inventory.find( {} )
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:
var filter = Builders<BsonDocument>.Filter.Empty;
var result = collection.Find(filter).ToList();cursor, err := coll.Find(
context.TODO(),
bson.D{},
)FindPublisher<Document> findPublisher = collection.find(new Document());FindIterable<Document> findIterable = collection.find(new Document());val flowInsertMany = collection
.find(empty())cursor = db.inventory.find({})const cursor = db.collection('inventory').find({});$cursor = $db->inventory->find([]);cursor = db.inventory.find({})client[:inventory].find({})var findObservable = collection.find(Document())This operation uses a query predicate of {}, which corresponds to the following SQL statement:
SELECT * FROM inventoryFor more information on the syntax of the method, see find().
For more information on the MongoDB Compass query bar, see Query Bar.
For more information on the syntax of the method, see mongoc_collection_find_with_opts.
For more information on the syntax of the method, see Find().
For more information on the syntax of the method, see com.mongodb.reactivestreams.client.MongoCollection.find.
For more information on the syntax of the method, see com.mongodb.client.MongoCollection.find.
For more information on the syntax of the method, see MongoCollection.find().
To see supported options for the find() method, see find().
For more information on the syntax of the method, see find().
For more information on the syntax of the method, see find.
For more information on the syntax of the method, see find().
For more information on the syntax of the method, see collection.find().
Specify Equality Condition
To specify equality conditions, use <field>:<value> expressions in the query filter document:
{ <field1>: <value1>, ... }To specify equality conditions, use <field>:<value> expressions in the query filter document:
{ <field1>: <value1>, ... }To specify equality conditions, use <field>:<value> expressions in the query filter document:
{ <field1>: <value1>, ... }To specify equality conditions, construct a filter using the Eq method:
Builders<BsonDocument>.Filter.Eq(<field>, <value>);To specify equality conditions, use the com.mongodb.client.model.Filters.eq method to create the query filter document:
and(eq(<field1>, <value1>), eq(<field2>, <value2>) ...)To specify equality conditions, use the com.mongodb.client.model.Filters.eq_ method to create the query filter document:
and(eq(<field1>, <value1>), eq(<field2>, <value2>) ...)To specify equality conditions, use the Filters.eq() method to create the query filter document:
and(eq(<field1>, <value1>), eq(<field2>, <value2>) ...)To specify equality conditions, use <field>:<value> expressions in the query filter document:
{ <field1>: <value1>, ... }To specify equality conditions, use <field>:<value> expressions in the query filter document:
{ <field1>: <value1>, ... }To specify equality conditions, use <field> => <value> expressions in the query filter document:
[ <field1> => <value1>, ... ]To specify equality conditions, use <field>:<value> expressions in the query filter document:
{ <field1>: <value1>, ... }To specify equality conditions, use <field> => <value> expressions in the query filter document:
{ <field1> => <value1>, ... }To specify equality conditions, use the com.mongodb.client.model.Filters.eq_ method to create the query filter document:
and(equal(<field1>, <value1>), equal(<field2>, <value2>) ...)The following example selects from the inventory collection all documents where the status equals "D":
db.inventory.find( { status: "D" } )Copy the following filter into the Compass query bar and click Find:
{ status: "D" }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);var filter = Builders<BsonDocument>.Filter.Eq("status", "D");
var result = collection.Find(filter).ToList();cursor, err := coll.Find(
context.TODO(),
bson.D{{"status", "D"}},
)findPublisher = collection.find(eq("status", "D"));findIterable = collection.find(eq("status", "D"));val findFlow = collection
.find(eq("status", "D"))cursor = db.inventory.find({"status": "D"})const cursor = db.collection('inventory').find({ status: 'D' });$cursor = $db->inventory->find(['status' => 'D']);cursor = db.inventory.find({"status": "D"})client[:inventory].find(status: 'D')findObservable = collection.find(equal("status", "D"))This operation uses a query predicate of { status: "D" }, which corresponds to the following SQL statement:
SELECT * FROM inventory WHERE status = "D"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.
Specify Conditions Using Query Operators
A query filter document can use the query operators to specify conditions in the following form:
{ <field1>: { <operator1>: <value1> }, ... }A query filter document can use the query operators to specify conditions in the following form:
{ <field1>: { <operator1>: <value1> }, ... }A query filter document can use the query operators to specify conditions in the following form:
{ <field1>: { <operator1>: <value1> }, ... }In addition to the equality filter, MongoDB provides various query operators to specify filter conditions. Use the FilterDefinitionBuilder methods to create a filter document. For example:
var builder = Builders<BsonDocument>.Filter;
builder.And(builder.Eq(<field1>, <value1>), builder.Lt(<field2>, <value2>));In addition to the equality filter, MongoDB provides various query operators to specify filter conditions. Use the bson package to create query operators for filter documents. For example:
filter := bson.D{
{"$and", bson.A{
bson.D{{"field1", bson.D{{"$eq", value1}}}},
bson.D{{"field2", bson.D{{"$lt", value2}}}},
}},
}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>))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>))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>))A query filter document can use the query operators to specify conditions in the following form:
{ <field1>: { <operator1>: <value1> }, ... }A query filter document can use the query operators to specify conditions in the following form:
{ <field1>: { <operator1>: <value1> }, ... }A query filter document can use the query operators to specify conditions in the following form:
[ <field1> => [ <operator1> => <value1> ], ... ]A query filter document can use the query operators to specify conditions in the following form:
{ <field1>: { <operator1>: <value1> }, ... }A query filter document can use the query operators to specify conditions in the following form:
{ <field1> => { <operator1> => <value1> }, ... }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>), equal(<field3>, <value3>))The following example retrieves all documents from the inventory collection where status equals either "A" or "D":
db.inventory.find( { status: { $in: [ "A", "D" ] } } )Copy the following filter into the Compass query bar and click Find:
{ status: { $in: [ "A", "D" ] } }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);var filter = Builders<BsonDocument>.Filter.In("status", new[] { "A", "D" });
var result = collection.Find(filter).ToList();cursor, err := coll.Find(
context.TODO(),
bson.D{{"status", bson.D{{"$in", bson.A{"A", "D"}}}}})findPublisher = collection.find(in("status", "A", "D"));findIterable = collection.find(in("status", "A", "D"));val findFlow = collection
.find(`in`("status", "A", "D"))cursor = db.inventory.find({"status": {"$in": ["A", "D"]}})const cursor = db.collection('inventory').find({
status: { $in: ['A', 'D'] }
});$cursor = $db->inventory->find(['status' => ['$in' => ['A', 'D']]]);cursor = db.inventory.find({"status": {"$in": ["A", "D"]}})client[:inventory].find(status: { '$in' => [ 'A', 'D' ]})findObservable = collection.find(in("status", "A", "D"))Note
The operation uses a query predicate of { status: { $in: [ "A", "D" ] } }, which corresponds to the following SQL statement:
SELECT * FROM inventory WHERE status in ("A", "D")For the complete list of MongoDB query operators, see Query Predicates.
Specify AND Conditions
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.
The following example retrieves all documents in the inventory collection where the status equals "A" and qty is less than ($lt) 30:
db.inventory.find( { status: "A", qty: { $lt: 30 } } )Copy the following filter into the Compass query bar and click Find:
{ status: "A", qty: { $lt: 30 } }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);var builder = Builders<BsonDocument>.Filter;
var filter = builder.And(builder.Eq("status", "A"), builder.Lt("qty", 30));
var result = collection.Find(filter).ToList();cursor, err := coll.Find(
context.TODO(),
bson.D{
{"status", "A"},
{"qty", bson.D{{"$lt", 30}}},
})findPublisher = collection.find(and(eq("status", "A"), lt("qty", 30)));findIterable = collection.find(and(eq("status", "A"), lt("qty", 30)));val findFlow = collection
.find(and(eq("status", "A"), lt("qty", 30)))cursor = db.inventory.find({"status": "A", "qty": {"$lt": 30}})const cursor = db.collection('inventory').find({
status: 'A',
qty: { $lt: 30 }
});$cursor = $db->inventory->find([
'status' => 'A',
'qty' => ['$lt' => 30],
]);cursor = db.inventory.find({"status": "A", "qty": {"$lt": 30}})client[:inventory].find(status: 'A', qty: { '$lt' => 30 })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:
SELECT * FROM inventory WHERE status = "A" AND qty < 30See comparison operators for other MongoDB comparison operators.
Specify OR Conditions
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.
The following example retrieves all documents in the collection where the status equals "A" or qty is less than ($lt) 30:
db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )Copy the following filter into the Compass query bar and click Find:
{ $or: [ { status: "A" }, { qty: { $lt: 30 } } ] }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);var builder = Builders<BsonDocument>.Filter;
var filter = builder.Or(builder.Eq("status", "A"), builder.Lt("qty", 30));
var result = collection.Find(filter).ToList();cursor, err := coll.Find(
context.TODO(),
bson.D{
{"$or",
bson.A{
bson.D{{"status", "A"}},
bson.D{{"qty", bson.D{{"$lt", 30}}}},
}},
})findPublisher = collection.find(or(eq("status", "A"), lt("qty", 30)));findIterable = collection.find(or(eq("status", "A"), lt("qty", 30)));val findFlow = collection
.find(or(eq("status", "A"), lt("qty", 30)))cursor = db.inventory.find({"$or": [{"status": "A"}, {"qty": {"$lt": 30}}]})const cursor = db.collection('inventory').find({
$or: [{ status: 'A' }, { qty: { $lt: 30 } }]
});$cursor = $db->inventory->find([
'$or' => [
['status' => 'A'],
['qty' => ['$lt' => 30]],
],
]);cursor = db.inventory.find({"$or": [{"status": "A"}, {"qty": {"$lt": 30}}]})client[:inventory].find('$or' => [{ status: 'A' },
{ qty: { '$lt' => 30 } }
])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:
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
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:
db.inventory.find( {
status: "A",
$or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]
} )Copy the following filter into the Compass query bar and click Find:
{ status: "A", $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ] }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);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();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: ""}}},
}},
})findPublisher = collection.find(
and(eq("status", "A"),
or(lt("qty", 30), regex("item", "^p")))
);findIterable = collection.find(
and(eq("status", "A"),
or(lt("qty", 30), regex("item", "^p")))
);val findFlow = collection
.find(
and(eq("status", "A"),
or(lt("qty", 30), regex("item", "^p")))
)cursor = db.inventory.find(
{"status": "A", "$or": [{"qty": {"$lt": 30}}, {"item": {"$regex": "^p"}}]}
)const cursor = db.collection('inventory').find({
status: 'A',
$or: [{ qty: { $lt: 30 } }, { item: { $regex: '^p' } }]
});$cursor = $db->inventory->find([
'status' => 'A',
'$or' => [
['qty' => ['$lt' => 30]],
// Alternatively: ['item' => new \MongoDB\BSON\Regex('^p')]
['item' => ['$regex' => '^p']],
],
]);cursor = db.inventory.find(
{"status": "A", "$or": [{"qty": {"$lt": 30}}, {"item": {"$regex": "^p"}}]}
)client[:inventory].find(status: 'A',
'$or' => [{ qty: { '$lt' => 30 } },
{ item: { '$regex' => BSON::Regexp::Raw.new('^p') } }
])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:
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.
Query Documents with 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.
To project fields to return from a query in MongoDB Atlas, follow these steps:
In the MongoDB Atlas UI, go to the Clusters page for your project.
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.
- If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.
- If it's not already displayed, select your project from the Projects menu in the navigation bar.
- If it's not already displayed, click Clusters in the sidebar.
The Clusters page displays.
Navigate to the collection
- For the cluster that contains the sample data, click Browse Collections.
- In the left navigation pane, select the
sample_mflixdatabase. - Select the
moviescollection.
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 }Additional Query Tutorials其他查询教程
For additional query examples, see:有关其他查询示例,请参阅:
Behavior行为
Cursor游标
The db.collection.find() method returns a cursor to the matching documents.db.collection.find()方法将游标返回到匹配的文档。
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常见问题解答。
The mongoc_collection_find_with_opts method returns a cursor to the matching documents.
The MongoCollection.Find() method returns a cursor to the matching documents. See the MongoDB C# driver documentation for iterating over a cursor.
The Collection.Find function returns a Cursor to the matching documents. See the Cursor documentation for more information.
com.mongodb.reactivestreams.client.MongoCollection.find returns an instance of the com.mongodb.reactivestreams.client.FindPublisher interface.
The com.mongodb.client.MongoCollection.find method returns an instance of the com.mongodb.client.FindIterable interface.
The MongoCollection.find() method returns an instance of the FindFlow class.
The Collection.find() method returns a cursor.Collection.find()方法返回一个游标。
The MongoDB\\Collection::find() method returns a cursor to the matching documents. See the MongoDB PHP Library documentation for iterating over a cursor.
The pymongo.collection.Collection.find method returns a cursor to the matching documents. See the PyMongo documentation for iterating over a cursor.
The Mongo::Collection#find() method returns a CollectionView, which is an Enumerable. A Cursor is created when the View is enumerated; for example, by calling #to_a() or #each(). You can also get an Enumerator by calling #to_enum() on the View. See the Ruby driver API documentation for iterating over a cursor.
The collection.find() method returns the 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 当您使用MongoDB驱动程序或mongosh, the command returns a cursor that manages query results. The query results are not returned as an array of documents.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其他方法和选项
The following can also read documents from a collection:以下人员也可以从集合中读取文档:
Thedb.collection.findOne()methoddb.collection.findOne()方法The聚合管道中的$matchpipeline stage in an aggregation pipeline. The$matchpipeline stage provides access to MongoDB queries$match管道阶段。$match管道阶段提供对MongoDB查询的访问
Note
The db.collection.findOne() method performs the same operation as the db.collection.find() method with a limit of 1.
In addition to filter, MongoDB Compass also allows you to pass the following options to the query bar:
The following method can also read documents from a collection:
The following can also read documents from a collection:
- MongoCollection.FindOne()
- In aggregation pipeline, the
$matchpipeline stage provides access to MongoDB queries. See the MongoDB C# driver's LINQ documentation.
Note
The MongoCollection.FindOne() method performs the same operation as the MongoCollection.Find() method with a limit of 1.
The following can also read documents from a collection:以下人员也可以从集合中读取文档:
- Collection.FindOne
- In aggregation pipeline, the
$matchpipeline stage provides access to MongoDB queries. See Collection.Aggregate.
The following can also read documents from a collection:
- In the aggregation pipeline, the
$matchpipeline stage provides access to MongoDB queries. See the Java Synchronous Driver Aggregation Examples.
The following methods can also read documents from a collection:以下方法也可以从集合中读取文档:
- In an aggregation pipeline, the
$matchpipeline stage allows you to perform MongoDB queries. See the Kotlin Coroutine Driver Find Operation Examples to learn more.
The following can also read documents from a collection:以下人员也可以从集合中读取文档:
- Collection.findOne()
- In aggregation pipeline, the
$matchpipeline stage provides access to MongoDB queries. See the MongoDB Node.js Driver's aggregation tutorial.
Note
The Collection.findOne() method performs the same operation as the Collection.find() method with a limit of 1.
The following can also read documents from a collection:
MongoDB\\Collection::findOne()- In aggregation pipeline, the
$matchpipeline stage provides access to MongoDB queries. See the MongoDB PHP Library's aggregation example.
Note
The MongoDB\\Collection::findOne() method performs the same operation as the MongoDB\\Collection::find() method with a limit of 1.
The following can also read documents from a collection:
pymongo.collection.Collection.find_oneIn an aggregation pipeline, the在聚合管道中,$matchpipeline stage provides access to MongoDB queries.$match管道阶段提供对MongoDB查询的访问。See the PyMongo Aggregation Examples.请参阅PyMongo聚合示例。
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.
The following can also read documents from a collection:以下人员也可以从集合中读取文档:
In aggregation pipeline, the在聚合管道中,$matchpipeline stage provides access to MongoDB queries.$match管道阶段提供对MongoDB查询的访问。See the MongoDB Ruby driver's aggregation examples.请参阅MongoDB Ruby驱动程序的聚合示例。
The following can also read documents from a collection:以下人员也可以从集合中读取文档:
In aggregation pipeline, the在聚合管道中,$matchpipeline stage provides access to MongoDB queries.$match管道阶段提供对MongoDB查询的访问。See the MongoDB Scala driver's aggregate method.请参阅MongoDB Scala驱动程序的聚合方法。