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 an Array of 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。
MongoDB Shell
This page provides examples of query operations on an array of nested documents 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 query operations on an array of nested documents 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 on an array of nested documents 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实例中的测试数据库,然后创建inventory集合:
C#
This page provides examples of query operations on an array of nested documents using the 本页提供了使用MongoDB C#驱动程序中的MongoCollection.Find() method in the MongoDB C# Driver.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 on an array of nested documents 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 on an array of nested documents 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 on an array of nested documents 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 on an array of nested documents by using the 本页提供了使用MongoDB Kotlin协程驱动程序中的MongoCollection.find() method in the MongoDB Kotlin Coroutine Driver.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集合:
Motor
This page provides examples of query operations on an array of nested documents using the 此页面提供了使用Motor驱动程序中的motor.motor_asyncio.AsyncIOMotorCollection.find method in the Motor driver.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 on an array of nested documents using the 本页提供了使用MongoDB Node.js驱动程序中的Collection.find() method in the MongoDB Node.js Driver.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:
PHP
This page provides examples of query operations on an array of nested documents 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:
Python
This page provides examples of query operations on an array of nested documents 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:
Ruby
This page provides examples of query operations on an array of nested documents 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:
scala
This page provides examples of query operations on an array of nested documents 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:
MongoDB Shell
db.inventory.insertMany( [
{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
{ item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
{ item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
{ item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);Compass
[
{ "item": "journal", "instock": [ { "warehouse": "A", "qty": 5 }, { "warehouse": "C", "qty": 15 } ] },
{ "item": "notebook", "instock": [ { "warehouse": "C", "qty": 5 } ] },
{ "item": "paper", "instock": [ { "warehouse": "A", "qty": 60 }, { "warehouse": "B", "qty": 15 } ] },
{ "item": "planner", "instock": [ { "warehouse": "A", "qty": 40 }, { "warehouse": "B", "qty": 5 } ] },
{ "item": "postcard", "instock": [ { "warehouse": "B","qty": 15 }, { "warehouse": "C", "qty": 35 } ] }
]
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"),
"instock", "[",
"{",
"warehouse", BCON_UTF8 ("A"),
"qty", BCON_INT64 (5),
"}","{",
"warehouse", BCON_UTF8 ("C"),
"qty", BCON_INT64 (15),
"}",
"]");
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"),
"instock", "[",
"{",
"warehouse", BCON_UTF8 ("C"),
"qty", BCON_INT64 (5),
"}",
"]");
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"),
"instock", "[",
"{",
"warehouse", BCON_UTF8 ("A"),
"qty", BCON_INT64 (60),
"}","{",
"warehouse", BCON_UTF8 ("B"),
"qty", BCON_INT64 (15),
"}",
"]");
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"),
"instock", "[",
"{",
"warehouse", BCON_UTF8 ("A"),
"qty", BCON_INT64 (40),
"}","{",
"warehouse", BCON_UTF8 ("B"),
"qty", BCON_INT64 (5),
"}",
"]");
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"),
"instock", "[",
"{",
"warehouse", BCON_UTF8 ("B"),
"qty", BCON_INT64 (15),
"}","{",
"warehouse", BCON_UTF8 ("C"),
"qty", BCON_INT64 (35),
"}",
"]");
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
{
{ "item", "journal" },
{ "instock", new BsonArray
{
new BsonDocument { { "warehouse", "A" }, { "qty", 5 } },
new BsonDocument { { "warehouse", "C" }, { "qty", 15 } } }
}
},
new BsonDocument
{
{ "item", "notebook" },
{ "instock", new BsonArray
{
new BsonDocument { { "warehouse", "C" }, { "qty", 5 } } }
}
},
new BsonDocument
{
{ "item", "paper" },
{ "instock", new BsonArray
{
new BsonDocument { { "warehouse", "A" }, { "qty", 60 } },
new BsonDocument { { "warehouse", "B" }, { "qty", 15 } } }
}
},
new BsonDocument
{
{ "item", "planner" },
{ "instock", new BsonArray
{
new BsonDocument { { "warehouse", "A" }, { "qty", 40 } },
new BsonDocument { { "warehouse", "B" }, { "qty", 5 } } }
}
},
new BsonDocument
{
{ "item", "postcard" },
{ "instock", new BsonArray
{
new BsonDocument { { "warehouse", "B" }, { "qty", 15 } },
new BsonDocument { { "warehouse", "C" }, { "qty", 35 } } }
}
}
};
collection.InsertMany(documents);Go
docs := []any{
bson.D{
{"item", "journal"},
{"instock", bson.A{
bson.D{
{"warehouse", "A"},
{"qty", 5},
},
bson.D{
{"warehouse", "C"},
{"qty", 15},
},
}},
},
bson.D{
{"item", "notebook"},
{"instock", bson.A{
bson.D{
{"warehouse", "C"},
{"qty", 5},
},
}},
},
bson.D{
{"item", "paper"},
{"instock", bson.A{
bson.D{
{"warehouse", "A"},
{"qty", 60},
},
bson.D{
{"warehouse", "B"},
{"qty", 15},
},
}},
},
bson.D{
{"item", "planner"},
{"instock", bson.A{
bson.D{
{"warehouse", "A"},
{"qty", 40},
},
bson.D{
{"warehouse", "B"},
{"qty", 5},
},
}},
},
bson.D{
{"item", "postcard"},
{"instock", bson.A{
bson.D{
{"warehouse", "B"},
{"qty", 15},
},
bson.D{
{"warehouse", "C"},
{"qty", 35},
},
}},
},
}
result, err := coll.InsertMany(context.TODO(), docs)Java(Async)
Publisher<Success> insertManyPublisher = collection.insertMany(asList(
Document.parse("{ item: 'journal', instock: [ { warehouse: 'A', qty: 5 }, { warehouse: 'C', qty: 15 } ] }"),
Document.parse("{ item: 'notebook', instock: [ { warehouse: 'C', qty: 5 } ] }"),
Document.parse("{ item: 'paper', instock: [ { warehouse: 'A', qty: 60 }, { warehouse: 'B', qty: 15 } ] }"),
Document.parse("{ item: 'planner', instock: [ { warehouse: 'A', qty: 40 }, { warehouse: 'B', qty: 5 } ] }"),
Document.parse("{ item: 'postcard', instock: [ { warehouse: 'B', qty: 15 }, { warehouse: 'C', qty: 35 } ] }")
));Java(Sync)
collection.insertMany(asList(
Document.parse("{ item: 'journal', instock: [ { warehouse: 'A', qty: 5 }, { warehouse: 'C', qty: 15 } ] }"),
Document.parse("{ item: 'notebook', instock: [ { warehouse: 'C', qty: 5 } ] }"),
Document.parse("{ item: 'paper', instock: [ { warehouse: 'A', qty: 60 }, { warehouse: 'B', qty: 15 } ] }"),
Document.parse("{ item: 'planner', instock: [ { warehouse: 'A', qty: 40 }, { warehouse: 'B', qty: 5 } ] }"),
Document.parse("{ item: 'postcard', instock: [ { warehouse: 'B', qty: 15 }, { warehouse: 'C', qty: 35 } ] }")
));Kotlin(Coroutine)
collection.insertMany(
listOf(
Document("item", "journal")
.append("instock", listOf(
Document("warehouse", "A").append("qty", 5),
Document("warehouse", "C").append("qty", 15)
)),
Document("item", "notebook")
.append("instock", listOf(
Document("warehouse", "C").append("qty", 5)
)),
Document("item", "paper")
.append("instock", listOf(
Document("warehouse", "A").append("qty", 60),
Document("warehouse", "B").append("qty", 15)
)),
Document("item", "planner")
.append("instock", listOf(
Document("warehouse", "A").append("qty", 40),
Document("warehouse", "B").append("qty", 5)
)),
Document("item", "postcard")
.append("instock", listOf(
Document("warehouse", "B").append("qty", 15),
Document("warehouse", "C").append("qty", 35)
)),
)
)Motor
# Subdocument key order matters in a few of these examples so we have
# to use bson.son.SON instead of a Python dict.
from bson.son import SON
await db.inventory.insert_many(
[
{
"item": "journal",
"instock": [
SON([("warehouse", "A"), ("qty", 5)]),
SON([("warehouse", "C"), ("qty", 15)]),
],
},
{"item": "notebook", "instock": [SON([("warehouse", "C"), ("qty", 5)])]},
{
"item": "paper",
"instock": [
SON([("warehouse", "A"), ("qty", 60)]),
SON([("warehouse", "B"), ("qty", 15)]),
],
},
{
"item": "planner",
"instock": [
SON([("warehouse", "A"), ("qty", 40)]),
SON([("warehouse", "B"), ("qty", 5)]),
],
},
{
"item": "postcard",
"instock": [
SON([("warehouse", "B"), ("qty", 15)]),
SON([("warehouse", "C"), ("qty", 35)]),
],
},
]
)Node.js
await db.collection('inventory').insertMany([
{
item: 'journal',
instock: [
{ warehouse: 'A', qty: 5 },
{ warehouse: 'C', qty: 15 }
]
},
{
item: 'notebook',
instock: [{ warehouse: 'C', qty: 5 }]
},
{
item: 'paper',
instock: [
{ warehouse: 'A', qty: 60 },
{ warehouse: 'B', qty: 15 }
]
},
{
item: 'planner',
instock: [
{ warehouse: 'A', qty: 40 },
{ warehouse: 'B', qty: 5 }
]
},
{
item: 'postcard',
instock: [
{ warehouse: 'B', qty: 15 },
{ warehouse: 'C', qty: 35 }
]
}
]);PHP
$insertManyResult = $db->inventory->insertMany([
[
'item' => 'journal',
'instock' => [
['warehouse' => 'A', 'qty' => 5],
['warehouse' => 'C', 'qty' => 15],
],
],
[
'item' => 'notebook',
'instock' => [
['warehouse' => 'C', 'qty' => 5],
],
],
[
'item' => 'paper',
'instock' => [
['warehouse' => 'A', 'qty' => 60],
['warehouse' => 'B', 'qty' => 15],
],
],
[
'item' => 'planner',
'instock' => [
['warehouse' => 'A', 'qty' => 40],
['warehouse' => 'B', 'qty' => 5],
],
],
[
'item' => 'postcard',
'instock' => [
['warehouse' => 'B', 'qty' => 15],
['warehouse' => 'C', 'qty' => 35],
],
],
]);Python
db.inventory.insert_many(
[
{
"item": "journal",
"instock": [
{"warehouse": "A", "qty": 5},
{"warehouse": "C", "qty": 15},
],
},
{"item": "notebook", "instock": [{"warehouse": "C", "qty": 5}]},
{
"item": "paper",
"instock": [
{"warehouse": "A", "qty": 60},
{"warehouse": "B", "qty": 15},
],
},
{
"item": "planner",
"instock": [
{"warehouse": "A", "qty": 40},
{"warehouse": "B", "qty": 5},
],
},
{
"item": "postcard",
"instock": [
{"warehouse": "B", "qty": 15},
{"warehouse": "C", "qty": 35},
],
},
]
)Ruby
client[:inventory].insert_many([{ item: 'journal',
instock: [ { warehouse: 'A', qty: 5 },
{ warehouse: 'C', qty: 15 }] },
{ item: 'notebook',
instock: [ { warehouse: 'C', qty: 5 }] },
{ item: 'paper',
instock: [ { warehouse: 'A', qty: 60 },
{ warehouse: 'B', qty: 15 }] },
{ item: 'planner',
instock: [ { warehouse: 'A', qty: 40 },
{ warehouse: 'B', qty: 5 }] },
{ item: 'postcard',
instock: [ { warehouse: 'B', qty: 15 },
{ warehouse: 'C', qty: 35 }] }
])scala
collection.insertMany(Seq(
Document("""{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] }"""),
Document("""{ item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] }"""),
Document("""{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] }"""),
Document("""{ item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] }"""),
Document("""{ item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }""")
)).execute()Query for a Document Nested in an Array查询嵌套在数组中的文档
The following example selects all documents where an element in the 以下示例选择instock array matches the specified document:instock数组中的元素与指定文档匹配的所有文档:
MongoDB Shell
db.inventory.find( { "instock": { warehouse: "A", qty: 5 } } )Compass
Copy the following filter into the Compass query bar and click Find:将以下筛选器复制到Compass查询栏中,然后单击“查找”:
{ "instock": { warehouse: "A", qty: 5 } }C
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;
collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW (
"instock", "{",
"warehouse", BCON_UTF8 ("A"),
"qty", BCON_INT64 (5),
"}");
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);C#
var filter = Builders<BsonDocument>.Filter.AnyEq("instock", new BsonDocument { { "warehouse", "A" }, { "qty", 5 } });
var result = collection.Find(filter).ToList();Go
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"instock", bson.D{
{"warehouse", "A"},
{"qty", 5},
}},
})Java(Async)
FindPublisher<Document> findPublisher = collection.find(eq("instock", Document.parse("{ warehouse: 'A', qty: 5 }")));Java(Sync)
FindIterable<Document> findIterable = collection.find(eq("instock", Document.parse("{ warehouse: 'A', qty: 5 }")));Kotlin(Coroutine)
val findFlow = collection
.find(eq("instock", Document.parse("{ warehouse: 'A', qty: 5 }")))Motor
cursor = db.inventory.find({"instock": SON([("warehouse", "A"), ("qty", 5)])})Node.js
const cursor = db.collection('inventory').find({
instock: { warehouse: 'A', qty: 5 }
});PHP
$cursor = $db->inventory->find(['instock' => ['warehouse' => 'A', 'qty' => 5]]);Python
cursor = db.inventory.find({"instock": {"warehouse": "A", "qty": 5}})Ruby
client[:inventory].find(instock: { warehouse: 'A', qty: 5 })scala
var findObservable = collection.find(equal("instock", Document("warehouse" -> "A", "qty" -> 5)))Equality matches on the whole embedded/nested document require an exact match of the specified document, including the field order. For example, the following query does not match any documents in the 整个嵌入/嵌套文档上的相等匹配要求与指定文档完全匹配,包括字段顺序。例如,以下查询与inventory collection:inventory集合中的任何文档都不匹配:
MongoDB Shell
db.inventory.find( { "instock": { qty: 5, warehouse: "A" } } )Compass
instock: { qty: 5, warehouse: 'A' }C
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;
collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW (
"instock", "{",
"qty", BCON_INT64 (5),
"warehouse", BCON_UTF8 ("A"),
"}");
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);C#
var filter = Builders<BsonDocument>.Filter.AnyEq("instock", new BsonDocument { { "qty", 5 }, { "warehouse", "A" } });
var result = collection.Find(filter).ToList();Go
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"instock", bson.D{
{"qty", 5},
{"warehouse", "A"},
}},
})Java(Async)
findPublisher = collection.find(eq("instock", Document.parse("{ qty: 5, warehouse: 'A' }")));Java(Sync)
findIterable = collection.find(eq("instock", Document.parse("{ qty: 5, warehouse: 'A' }")));Kotlin(Coroutine)
val findFlow = collection
.find(eq("instock", Document.parse("{ qty: 5, warehouse: 'A' }")))Motor
cursor = db.inventory.find({"instock": SON([("qty", 5), ("warehouse", "A")])})Node.js
const cursor = db.collection('inventory').find({
instock: { qty: 5, warehouse: 'A' }
});PHP
$cursor = $db->inventory->find(['instock' => ['qty' => 5, 'warehouse' => 'A']]);Python
cursor = db.inventory.find({"instock": {"qty": 5, "warehouse": "A"}})Ruby
client[:inventory].find(instock: { qty: 5, warehouse: 'A' } )scala
findObservable = collection.find(equal("instock", Document("qty" -> 5, "warehouse" -> "A")))Specify a Query Condition on a Field in an Array of Documents在文档数组中的字段上指定查询条件
Specify a Query Condition on a Field Embedded in an Array of Documents在文档数组中嵌入的字段上指定查询条件
If you do not know the index position of the document nested in the array, concatenate the name of the array field, with a dot (如果您不知道嵌套在数组中的文档的索引位置,请将数组字段的名称与嵌套文档中的点(.) and the name of the field in the nested document..)和字段名称连接起来。
The following example selects all documents where the 以下示例选择instock array has at least one embedded document that contains the field qty whose value is less than or equal to 20:instock数组中至少有一个嵌入式文档包含值小于或等于20的字段qty的所有文档:
MongoDB Shell
db.inventory.find( { 'instock.qty': { $lte: 20 } } )Compass
Copy the following filter into the Compass query bar and click Find:将以下筛选器复制到Compass查询栏中,然后单击“查找”:
{ 'instock.qty': { $lte: 20 } }

C
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;
collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW (
"instock.qty", "{",
"$lte", BCON_INT64 (20),
"}");
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);C#
var filter = Builders<BsonDocument>.Filter.Lte("instock.qty", 20);
var result = collection.Find(filter).ToList();Go
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"instock.qty", bson.D{
{"$lte", 20},
}},
})Java(Async)
findPublisher = collection.find(lte("instock.qty", 20));Java(Sync)
findIterable = collection.find(lte("instock.qty", 20));Kotlin(Coroutine)
val findFlow = collection
.find(lte("instock.qty", 20))Motor
cursor = db.inventory.find({"instock.qty": {"$lte": 20}})Node.js
const cursor = db.collection('inventory').find({
'instock.qty': { $lte: 20 }
});PHP
$cursor = $db->inventory->find(['instock.qty' => ['$lte' => 20]]);Python
cursor = db.inventory.find({"instock.qty": {"$lte": 20}})Ruby
client[:inventory].find('instock.qty' => { '$lte' => 20 })scala
findObservable = collection.find(lte("instock.qty", 20))Use the Array Index to Query for a Field in the Embedded Document使用数组索引查询嵌入式文档中的字段
Using dot notation, you can specify query conditions for field in a document at a particular index or position of the array. The array uses zero-based indexing.使用点表示法,您可以在数组的特定索引或位置为文档中的字段指定查询条件。数组使用从零开始的索引。
Note
When querying using dot notation, the field and index must be inside quotation marks.使用点表示法查询时,字段和索引必须在引号内。
The following example selects all documents where the 以下示例选择所有instock数组的第一个元素是包含值小于或等于instock array has as its first element a document that contains the field qty whose value is less than or equal to 20:20的字段qty的文档的文档:
MongoDB Shell
db.inventory.find( { 'instock.0.qty': { $lte: 20 } } )Compass
Copy the following filter into the Compass query bar and click Find:将以下筛选器复制到Compass查询栏中,然后单击“查找”:
{ 'instock.0.qty': { $lte: 20 } }

C
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;
collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW (
"instock.0.qty", "{",
"$lte", BCON_INT64 (20),
"}");
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);C#
var filter = Builders<BsonDocument>.Filter.Lte("instock.0.qty", 20);
var result = collection.Find(filter).ToList();Go
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"instock.0.qty", bson.D{
{"$lte", 20},
}},
})Java(Async)
findPublisher = collection.find(lte("instock.0.qty", 20));Java(Sync)
findIterable = collection.find(lte("instock.0.qty", 20));Kotlin(Coroutine)
val findFlow = collection
.find(lte("instock.0.qty", 20))Motor
cursor = db.inventory.find({"instock.0.qty": {"$lte": 20}})Node.js
const cursor = db.collection('inventory').find({
'instock.0.qty': { $lte: 20 }
});PHP
$cursor = $db->inventory->find(['instock.0.qty' => ['$lte' => 20]]);Python
cursor = db.inventory.find({"instock.0.qty": {"$lte": 20}})Ruby
client[:inventory].find('instock.0.qty' => { '$lte' => 20 })scala
findObservable = collection.find(lte("instock.0.qty", 20))Specify Multiple Conditions for Array of Documents为文档数组指定多个条件
When specifying conditions on more than one field nested in an array of documents, you can specify the query such that either a single document meets these condition or any combination of documents (including a single document) in the array meets the conditions.在为嵌套在文档数组中的多个字段指定条件时,您可以指定查询,使单个文档满足这些条件,或者数组中的任何文档组合(包括单个文档)满足这些条件。
A Single Nested Document Meets Multiple Query Conditions on Nested Fields单个嵌套文档在嵌套字段上满足多个查询条件
Use 使用$elemMatch operator to specify multiple criteria on an array of embedded documents such that at least one embedded document satisfies all the specified criteria.$elemMatch运算符在嵌入式文档数组上指定多个条件,以便至少有一个嵌入式文档满足所有指定的条件。
The following example queries for documents where the 以下示例查询instock array has at least one embedded document that contains both the field qty equal to 5 and the field warehouse equal to A:instock数组中至少有一个嵌入文档的文档,该文档包含等于5的字段qty和等于A的字段仓库:
MongoDB Shell
db.inventory.find( { "instock": { $elemMatch: { qty: 5, warehouse: "A" } } } )Compass
Copy the following filter into the Compass query bar and click Find:将以下筛选器复制到Compass查询栏中,然后单击“查找”:
{ "instock": { $elemMatch: { qty: 5, warehouse: "A" } } }

C
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;
collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW (
"instock", "{",
"$elemMatch", "{",
"qty", BCON_INT64 (5),
"warehouse", BCON_UTF8 ("A"),
"}",
"}");
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);C#
var filter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>("instock", new BsonDocument { { "qty", 5 }, { "warehouse", "A" } });
var result = collection.Find(filter).ToList();Go
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"instock", bson.D{
{"$elemMatch", bson.D{
{"qty", 5},
{"warehouse", "A"},
}},
}},
})Java(Async)
findPublisher = collection.find(elemMatch("instock", Document.parse("{ qty: 5, warehouse: 'A' }")));Java(Sync)
findIterable = collection.find(elemMatch("instock", Document.parse("{ qty: 5, warehouse: 'A' }")));Kotlin(Coroutine)
val findFlow = collection
.find(elemMatch("instock", Document.parse("{ qty: 5, warehouse: 'A' }")))Motor
cursor = db.inventory.find({"instock": {"$elemMatch": {"qty": 5, "warehouse": "A"}}})Node.js
const cursor = db.collection('inventory').find({
instock: { $elemMatch: { qty: 5, warehouse: 'A' } }
});PHP
$cursor = $db->inventory->find(['instock' => ['$elemMatch' => ['qty' => 5, 'warehouse' => 'A']]]);Python
cursor = db.inventory.find({"instock": {"$elemMatch": {"qty": 5, "warehouse": "A"}}})Ruby
client[:inventory].find(instock: { '$elemMatch' => { qty: 5,
warehouse: 'A' } })scala
findObservable = collection.find(elemMatch("instock", Document("qty" -> 5, "warehouse" -> "A")))The following example queries for documents where the 以下示例查询instock array has at least one embedded document that contains the field qty that is greater than 10 and less than or equal to 20:instock数组中至少有一个嵌入式文档包含大于10且小于或等于20的字段qty的文档:
MongoDB Shell
db.inventory.find( { "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } } )Compass
Copy the following filter into the Compass query bar and click Find:将以下筛选器复制到Compass查询栏中,然后单击“查找”:
{ "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } }

C
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;
collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW (
"instock", "{",
"$elemMatch", "{",
"qty", "{",
"$gt", BCON_INT64 (10),
"$lte", BCON_INT64 (20),
"}",
"}",
"}");
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);C#
var filter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>("instock", new BsonDocument { { "qty", new BsonDocument { { "$gt", 10 }, { "$lte", 20 } } } });
var result = collection.Find(filter).ToList();Go
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"instock", bson.D{
{"$elemMatch", bson.D{
{"qty", bson.D{
{"$gt", 10},
{"$lte", 20},
}},
}},
}},
})Java(Async)
findPublisher = collection.find(elemMatch("instock", Document.parse("{ qty: { $gt: 10, $lte: 20 } }")));Java(Sync)
findIterable = collection.find(elemMatch("instock", Document.parse("{ qty: { $gt: 10, $lte: 20 } }")));Kotlin(Coroutine)
val findFlow = collection
.find(elemMatch("instock", Document.parse("{ qty: { \$gt: 10, \$lte: 20 } }")))Motor
cursor = db.inventory.find({"instock": {"$elemMatch": {"qty": {"$gt": 10, "$lte": 20}}}})Node.js
const cursor = db.collection('inventory').find({
instock: { $elemMatch: { qty: { $gt: 10, $lte: 20 } } }
});PHP
$cursor = $db->inventory->find(['instock' => ['$elemMatch' => ['qty' => ['$gt' => 10, '$lte' => 20]]]]);Python
cursor = db.inventory.find({"instock": {"$elemMatch": {"qty": {"$gt": 10, "$lte": 20}}}})Ruby
client[:inventory].find(instock: { '$elemMatch' => { qty: { '$gt' => 10,
'$lte' => 20 } } })scala
findObservable = collection.find(elemMatch("instock", Document("""{ qty: { $gt: 10, $lte: 20 } }""")))Combination of Elements Satisfies the Criteria元素组合满足标准
If the compound query conditions on an array field do not use the 如果数组字段上的复合查询条件不使用$elemMatch operator, the query selects those documents whose array contains any combination of elements that satisfies the conditions.$elemMatch运算符,则查询将选择其数组包含满足条件的任何元素组合的文档。
For example, the following query matches documents where any document nested in the 例如,以下查询匹配的文档中,嵌套在instock array has the qty field greater than 10 and any document (but not necessarily the same embedded document) in the array has the qty field less than or equal to 20:instock数组中的任何文档的qty字段都大于10,而数组中的所有文档(但不一定是同一个嵌入式文档)的qty字段小于或等于20:
MongoDB Shell
db.inventory.find( { "instock.qty": { $gt: 10, $lte: 20 } } )Compass
Copy the following filter into the Compass query bar and click Find:将以下筛选器复制到Compass查询栏中,然后单击“查找”:
{ "instock.qty": { $gt: 10, $lte: 20 } }

C
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;
collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW (
"instock.qty", "{",
"$gt", BCON_INT64 (10),
"$lte", BCON_INT64 (20),
"}");
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);C#
var builder = Builders<BsonDocument>.Filter;
var filter = builder.And(builder.Gt("instock.qty", 10), builder.Lte("instock.qty", 20));
var result = collection.Find(filter).ToList();Go
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"instock.qty", bson.D{
{"$gt", 10},
{"$lte", 20},
}},
})Java(Async)
findPublisher = collection.find(and(gt("instock.qty", 10), lte("instock.qty", 20)));Java(Sync)
findIterable = collection.find(and(gt("instock.qty", 10), lte("instock.qty", 20)));Kotlin(Coroutine)
val findFlow = collection
.find(and(gt("instock.qty", 10), lte("instock.qty", 20)))Motor
cursor = db.inventory.find({"instock.qty": {"$gt": 10, "$lte": 20}})Node.js
const cursor = db.collection('inventory').find({
'instock.qty': { $gt: 10, $lte: 20 }
});PHP
$cursor = $db->inventory->find(['instock.qty' => ['$gt' => 10, '$lte' => 20]]);Python
cursor = db.inventory.find({"instock.qty": {"$gt": 10, "$lte": 20}})Ruby
client[:inventory].find('instock.qty' => { '$gt' => 10, '$lte' => 20 })scala
findObservable = collection.find(and(gt("instock.qty", 10), lte("instock.qty", 20)))The following example queries for documents where the 以下示例查询的文档中,instock array has at least one embedded document that contains the field qty equal to 5 and at least one embedded document (but not necessarily the same embedded document) that contains the field warehouse equal to A:instock数组至少有一个包含字段qty等于5的嵌入式文档,以及至少一个包含等于A的字段warehouse(仓库)的嵌入式文档(但不一定是同一个嵌入式文档):
MongoDB Shell
db.inventory.find( { "instock.qty": 5, "instock.warehouse": "A" } )Compass
Copy the following filter into the Compass query bar and click Find:将以下筛选器复制到Compass查询栏中,然后单击“查找”:
{ "instock.qty": 5, "instock.warehouse": "A" }

C
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;
collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW (
"instock.qty", BCON_INT64 (5),
"instock.warehouse", BCON_UTF8 ("A"));
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);C#
var builder = Builders<BsonDocument>.Filter;
var filter = builder.And(builder.Eq("instock.qty", 5), builder.Eq("instock.warehouse", "A"));
var result = collection.Find(filter).ToList();Go
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"instock.qty", 5},
{"instock.warehouse", "A"},
})Java(Async)
findPublisher = collection.find(and(eq("instock.qty", 5), eq("instock.warehouse", "A")));Java(Sync)
findIterable = collection.find(and(eq("instock.qty", 5), eq("instock.warehouse", "A")));Kotlin(Coroutine)
val findFlow = collection
.find(and(eq("instock.qty", 5), eq("instock.warehouse", "A")))Motor
cursor = db.inventory.find({"instock.qty": 5, "instock.warehouse": "A"})Node.js
const cursor = db.collection('inventory').find({
'instock.qty': 5,
'instock.warehouse': 'A'
});PHP
$cursor = $db->inventory->find(['instock.qty' => 5, 'instock.warehouse' => 'A']);Python
cursor = db.inventory.find({"instock.qty": 5, "instock.warehouse": "A"})Ruby
client[:inventory].find('instock.qty' => 5,
'instock.warehouse' => 'A')scala
findObservable = collection.find(and(equal("instock.qty", 5), equal("instock.warehouse", "A")))Query an Array of Documents 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 an array of documents in MongoDB Atlas, follow these steps:要查询MongoDB Atlas中的文档数组,请执行以下步骤:
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预览文档。
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.如果尚未显示,请单击侧栏中的“集群”。
Navigate to the collection导航到集合
For the cluster that contains the sample data, click Browse Collections.对于包含示例数据的集群,单击“浏览集合”。In the left navigation pane, select the sample_training database.在左侧导航窗格中,选择sample_training数据库。Select the grades collection.选择grades集合。
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:将以下查询筛选器文档复制到筛选器搜索栏中:
{"scores.type": "exam"}Click Apply单击“应用”
This query filter returns all documents in the 此查询筛选器返回sample_training.grades collection that contain a subdocument in the scores array where type is set to exam. sample_training.grades集合中的所有文档,这些文档包含scores数组中type设置为exam的子文档。The full document, including the entire 返回完整文档,包括整个scores array, is returned. scores数组。For more information on modifying the returned array, see Project Specific Array Elements in the Returned Array.有关修改返回数组的更多信息,请参阅返回数组中的项目特定数组元素。
Additional Query Tutorials其他查询教程
For additional query examples, see:有关其他查询示例,请参阅: