查询嵌套文档的数组
您可以使用以下方法在 MongoDB 中查询文档
您的编程语言驱动程序。
的MongoDB Atlas UI. 有关更多信息,请参阅 使用 MongoDB Atlas 查询文档数组。
➤使用右上角的选择您的语言下拉菜单设置以下示例的语言或选择MongoDB Compass。
本页面提供了以下示例:在嵌套文档数组上执行查询操作使用db.collection.find()
方法在 mongosh
.
本页面的示例使用 inventory
集合。连接到您的MongoDB实例中的测试数据库,然后使用 MongoDB Compass.
本页面提供了以下示例:在嵌套文档数组上执行查询操作使用
本页面的示例使用 inventory
集合。连接到您的MongoDB实例中的测试数据库,然后使用 MongoDB Compass.
本页面提供了以下示例:在嵌套文档数组上执行查询操作mongoc_collection_find_with_opts.
本页面的示例使用 inventory
集合。连接到您的MongoDB实例中的测试数据库,然后使用 MongoDB Compass.
本页面提供了以下示例:在嵌套文档数组上执行查询操作使用MongoCollection.Find()方法在MongoDB C# Driver中。
本页面的示例使用 inventory
集合。连接到您的MongoDB实例中的测试数据库,然后使用 MongoDB Compass.
本页面提供了以下示例:在嵌套文档数组上执行查询操作使用Collection.Find函数在MongoDB Go Driver中。
本页面的示例使用 inventory
集合。连接到您的MongoDB实例中的测试数据库,然后使用 MongoDB Compass.
本页面提供了以下示例:在嵌套文档数组上执行查询操作使用MongoDB的com.mongodb.reactivestreams.client.MongoCollection.find方法在Java Reactive Streams Driver中。
本页面的示例使用 inventory
集合。连接到您的MongoDB实例中的测试数据库,然后使用 MongoDB Compass.
本页面提供了以下示例:在嵌套文档数组上执行查询操作使用MongoDB的com.mongodb.client.MongoCollection.find方法,该方法位于Java 同步驱动程序中。
提示
该驱动程序提供了com.mongodb.client.model.Filters辅助方法,以方便创建过滤文档。本页面上的示例使用这些方法创建过滤文档。
本页面的示例使用 inventory
集合。连接到您的MongoDB实例中的测试数据库,然后使用 MongoDB Compass.
本页面提供了以下示例:在嵌套文档数组上执行查询操作通过使用 MongoDB 的 MongoCollection.find() 方法,在 MongoDB Kotlin Coroutine Driver. 中。
提示
此驱动程序提供了 com.mongodb.client.model.Filters 辅助方法,以方便创建过滤器文档。本页面上的示例使用这些方法创建过滤器文档。
本页面的示例使用 inventory
集合。连接到您的MongoDB实例中的测试数据库,然后使用 MongoDB Compass.
本页面提供了以下示例:在嵌套文档数组上执行查询操作在 motor.motor_asyncio.AsyncIOMotorCollection.find
方法中使用了 Motor 驱动程序。
本页面的示例使用 inventory
集合。连接到您的MongoDB实例中的测试数据库,然后使用 MongoDB Compass.
本页面提供了以下示例:在嵌套文档数组上执行查询操作使用Collection.find()方法在MongoDB Node.js Driver
本页面的示例使用 inventory
集合。连接到您的MongoDB实例中的测试数据库,然后使用 MongoDB Compass.
本页面提供了以下示例:在嵌套文档数组上执行查询操作使用 MongoDB::Collection::find() 方法,在 MongoDB Perl 驱动程序 中。
本页面的示例使用 inventory
集合。连接到您的MongoDB实例中的测试数据库,然后使用 MongoDB Compass.
本页面提供了以下示例:在嵌套文档数组上执行查询操作使用 MongoDB\\Collection::find()
方法,在 MongoDB PHP 库 中。
本页面的示例使用 inventory
集合。连接到您的MongoDB实例中的测试数据库,然后使用 MongoDB Compass.
本页面提供了以下示例:在嵌套文档数组上执行查询操作使用 pymongo.collection.Collection.find
方法,在 PyMongo Python 驱动程序中。
本页面的示例使用 inventory
集合。连接到您的MongoDB实例中的测试数据库,然后使用 MongoDB Compass.
本页面提供了以下示例:在嵌套文档数组上执行查询操作使用Mongo::Collection#find()方法,该方法位于MongoDB Ruby Driver.
本页面的示例使用 inventory
集合。连接到您的MongoDB实例中的测试数据库,然后使用 MongoDB Compass.
本页面提供了以下示例:在嵌套文档数组上执行查询操作使用collection.find()方法,该方法位于MongoDB Scala Driver。
本页面的示例使用 inventory
集合。连接到您的MongoDB实例中的测试数据库,然后使用 MongoDB Compass.
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 } ] } ]);
[ { "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 } ] } ]
有关在MongoDB Compass中插入文档的说明,请参阅插入文档。
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); }
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);
docs := []interface{}{ 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)
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 } ] }") ));
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 } ] }") ));
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) )), ) )
# 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)]), ], }, ] )
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 } ] } ]);
# Subdocument key order matters in this example so we have # to use Tie::IxHash instead of a regular, unordered Perl hash. $db->coll("inventory")->insert_many( [ { item => "journal", instock => [ Tie::IxHash->new( warehouse => "A", qty => 5 ), Tie::IxHash->new( warehouse => "C", qty => 15 ) ] }, { item => "notebook", instock => [ Tie::IxHash->new( warehouse => "C", qty => 5 ) ] }, { item => "paper", instock => [ Tie::IxHash->new( warehouse => "A", qty => 60 ), Tie::IxHash->new( warehouse => "B", qty => 15 ) ] }, { item => "planner", instock => [ Tie::IxHash->new( warehouse => "A", qty => 40 ), Tie::IxHash->new( warehouse => "B", qty => 5 ) ] }, { item => "postcard", instock => [ Tie::IxHash->new( warehouse => "B", qty => 15 ), Tie::IxHash->new( warehouse => "C", qty => 35 ) ] } ] );
$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], ], ], ]);
# 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 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)]), ], }, ] )
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 }] } ])
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()
查询嵌套在数组中的文档
以下示例选择所有instock
数组中的元素与指定的文档匹配的文档
db.inventory.find( { "instock": { warehouse: "A", qty: 5 } } )
将以下过滤器复制到Compass查询栏中,然后单击查找:
{ "instock": { warehouse: "A", qty: 5 } }
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);
var filter = Builders<BsonDocument>.Filter.AnyEq("instock", new BsonDocument { { "warehouse", "A" }, { "qty", 5 } }); var result = collection.Find(filter).ToList();
cursor, err := coll.Find( context.TODO(), bson.D{ {"instock", bson.D{ {"warehouse", "A"}, {"qty", 5}, }}, })
FindPublisher<Document> findPublisher = collection.find(eq("instock", Document.parse("{ warehouse: 'A', qty: 5 }")));
FindIterable<Document> findIterable = collection.find(eq("instock", Document.parse("{ warehouse: 'A', qty: 5 }")));
val findFlow = collection .find(eq("instock", Document.parse("{ warehouse: 'A', qty: 5 }")))
cursor = db.inventory.find({"instock": SON([("warehouse", "A"), ("qty", 5)])})
const cursor = db.collection('inventory').find({ instock: { warehouse: 'A', qty: 5 } });
# Subdocument key order matters in this example so we have # to use Tie::IxHash instead of a regular, unordered Perl hash. $cursor = $db->coll("inventory")->find( { instock => Tie::IxHash->new( warehouse => "A", qty => 5 ) } );
$cursor = $db->inventory->find(['instock' => ['warehouse' => 'A', 'qty' => 5]]);
cursor = db.inventory.find({"instock": SON([("warehouse", "A"), ("qty", 5)])})
client[:inventory].find(instock: { warehouse: 'A', qty: 5 })
var findObservable = collection.find(equal("instock", Document("warehouse" -> "A", "qty" -> 5)))
在嵌入式/嵌套文档上执行完全匹配,需要指定文档的精确匹配,包括字段顺序。例如,以下查询在 inventory
集合中没有任何文档匹配
db.inventory.find( { "instock": { qty: 5, warehouse: "A" } } )
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);
var filter = Builders<BsonDocument>.Filter.AnyEq("instock", new BsonDocument { { "qty", 5 }, { "warehouse", "A" } }); var result = collection.Find(filter).ToList();
cursor, err := coll.Find( context.TODO(), bson.D{ {"instock", bson.D{ {"qty", 5}, {"warehouse", "A"}, }}, })
findPublisher = collection.find(eq("instock", Document.parse("{ qty: 5, warehouse: 'A' }")));
findIterable = collection.find(eq("instock", Document.parse("{ qty: 5, warehouse: 'A' }")));
val findFlow = collection .find(eq("instock", Document.parse("{ qty: 5, warehouse: 'A' }")))
cursor = db.inventory.find({"instock": SON([("qty", 5), ("warehouse", "A")])})
const cursor = db.collection('inventory').find({ instock: { qty: 5, warehouse: 'A' } });
# Subdocument key order matters in this example so we have # to use Tie::IxHash instead of a regular, unordered Perl hash. $cursor = $db->coll("inventory")->find( { instock => Tie::IxHash->new( qty => 5, warehouse => "A" ) } );
$cursor = $db->inventory->find(['instock' => ['qty' => 5, 'warehouse' => 'A']]);
cursor = db.inventory.find({"instock": SON([("qty", 5), ("warehouse", "A")])})
client[:inventory].find(instock: { qty: 5, warehouse: 'A' } )
findObservable = collection.find(equal("instock", Document("qty" -> 5, "warehouse" -> "A")))
在文档数组中的一个字段上指定查询条件
在文档数组中嵌入的字段上指定查询条件
如果您不知道数组中嵌套文档的索引位置,请将数组字段的名称与点(.
)以及嵌套文档中的字段名称连接起来。
以下示例选择所有 instock
数组中至少包含一个包含字段 qty
(其值小于或等于 20
)的嵌入式文档的文档。
db.inventory.find( { 'instock.qty': { $lte: 20 } } )
将以下过滤器复制到 Compass 查询栏中,然后点击 查找
{ 'instock.qty': { $lte: 20 } }

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);
var filter = Builders<BsonDocument>.Filter.Lte("instock.qty", 20); var result = collection.Find(filter).ToList();
cursor, err := coll.Find( context.TODO(), bson.D{ {"instock.qty", bson.D{ {"$lte", 20}, }}, })
findPublisher = collection.find(lte("instock.qty", 20));
findIterable = collection.find(lte("instock.qty", 20));
val findFlow = collection .find(lte("instock.qty", 20))
cursor = db.inventory.find({"instock.qty": {"$lte": 20}})
const cursor = db.collection('inventory').find({ 'instock.qty': { $lte: 20 } });
$cursor = $db->coll("inventory")->find( { 'instock.qty' => { '$lte' => 20 } } );
$cursor = $db->inventory->find(['instock.qty' => ['$lte' => 20]]);
cursor = db.inventory.find({"instock.qty": {"$lte": 20}})
client[:inventory].find('instock.qty' => { '$lte' => 20 })
findObservable = collection.find(lte("instock.qty", 20))
使用数组索引在嵌入式文档中查询字段
使用点表示法,您可以在特定索引或数组位置指定文档中字段的查询条件。数组使用基于0的索引。
注意
在点表示法查询中,字段和索引必须位于引号内。
以下示例选择所有instock
数组其第一个元素包含字段qty
的文档,且其值小于或等于20
db.inventory.find( { 'instock.0.qty': { $lte: 20 } } )
将以下过滤器复制到 Compass 查询栏中,然后点击 查找
{ 'instock.0.qty': { $lte: 20 } }

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);
var filter = Builders<BsonDocument>.Filter.Lte("instock.0.qty", 20); var result = collection.Find(filter).ToList();
cursor, err := coll.Find( context.TODO(), bson.D{ {"instock.0.qty", bson.D{ {"$lte", 20}, }}, })
findPublisher = collection.find(lte("instock.0.qty", 20));
findIterable = collection.find(lte("instock.0.qty", 20));
val findFlow = collection .find(lte("instock.0.qty", 20))
cursor = db.inventory.find({"instock.0.qty": {"$lte": 20}})
const cursor = db.collection('inventory').find({ 'instock.0.qty': { $lte: 20 } });
$cursor = $db->coll("inventory")->find( { 'instock.0.qty' => { '$lte' => 20 } } );
$cursor = $db->inventory->find(['instock.0.qty' => ['$lte' => 20]]);
cursor = db.inventory.find({"instock.0.qty": {"$lte": 20}})
client[:inventory].find('instock.0.qty' => { '$lte' => 20 })
findObservable = collection.find(lte("instock.0.qty", 20))
指定文档数组的多条件查询
当在文档数组中嵌套的多个字段上指定条件时,可以指定查询条件,使得单个文档满足这些条件或数组中的任何组合(包括单个文档)满足条件。
单个嵌套文档满足嵌套字段的多条件查询
使用$elemMatch
运算符来指定嵌入文档数组上的多个标准,使得至少一个嵌入文档满足所有指定的标准。
以下示例查询包含字段qty
等于5
且字段warehouse
等于A
的至少一个嵌入文档的instock
数组。
db.inventory.find( { "instock": { $elemMatch: { qty: 5, warehouse: "A" } } } )
将以下过滤器复制到 Compass 查询栏中,然后点击 查找
{ "instock": { $elemMatch: { qty: 5, warehouse: "A" } } }
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);
var filter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>("instock", new BsonDocument { { "qty", 5 }, { "warehouse", "A" } }); var result = collection.Find(filter).ToList();
cursor, err := coll.Find( context.TODO(), bson.D{ {"instock", bson.D{ {"$elemMatch", bson.D{ {"qty", 5}, {"warehouse", "A"}, }}, }}, })
findPublisher = collection.find(elemMatch("instock", Document.parse("{ qty: 5, warehouse: 'A' }")));
findIterable = collection.find(elemMatch("instock", Document.parse("{ qty: 5, warehouse: 'A' }")));
val findFlow = collection .find(elemMatch("instock", Document.parse("{ qty: 5, warehouse: 'A' }")))
cursor = db.inventory.find({"instock": {"$elemMatch": {"qty": 5, "warehouse": "A"}}})
const cursor = db.collection('inventory').find({ instock: { $elemMatch: { qty: 5, warehouse: 'A' } } });
$cursor = $db->coll("inventory")->find( { instock => { '$elemMatch' => { qty => 5, warehouse => "A" } } } );
$cursor = $db->inventory->find(['instock' => ['$elemMatch' => ['qty' => 5, 'warehouse' => 'A']]]);
cursor = db.inventory.find({"instock": {"$elemMatch": {"qty": 5, "warehouse": "A"}}})
client[:inventory].find(instock: { '$elemMatch' => { qty: 5, warehouse: 'A' } })
findObservable = collection.find(elemMatch("instock", Document("qty" -> 5, "warehouse" -> "A")))
以下示例查询包含字段qty
大于10
且小于或等于20
的至少一个嵌入文档的instock
数组。
db.inventory.find( { "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } } )
将以下过滤器复制到 Compass 查询栏中,然后点击 查找
{ "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } }
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);
var filter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>("instock", new BsonDocument { { "qty", new BsonDocument { { "$gt", 10 }, { "$lte", 20 } } } }); var result = collection.Find(filter).ToList();
cursor, err := coll.Find( context.TODO(), bson.D{ {"instock", bson.D{ {"$elemMatch", bson.D{ {"qty", bson.D{ {"$gt", 10}, {"$lte", 20}, }}, }}, }}, })
findPublisher = collection.find(elemMatch("instock", Document.parse("{ qty: { $gt: 10, $lte: 20 } }")));
findIterable = collection.find(elemMatch("instock", Document.parse("{ qty: { $gt: 10, $lte: 20 } }")));
val findFlow = collection .find(elemMatch("instock", Document.parse("{ qty: { \$gt: 10, \$lte: 20 } }")))
cursor = db.inventory.find({"instock": {"$elemMatch": {"qty": {"$gt": 10, "$lte": 20}}}})
const cursor = db.collection('inventory').find({ instock: { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } });
$cursor = $db->coll("inventory") ->find( { instock => { '$elemMatch' => { qty => { '$gt' => 10, '$lte' => 20 } } } } );
$cursor = $db->inventory->find(['instock' => ['$elemMatch' => ['qty' => ['$gt' => 10, '$lte' => 20]]]]);
cursor = db.inventory.find({"instock": {"$elemMatch": {"qty": {"$gt": 10, "$lte": 20}}}})
client[:inventory].find(instock: { '$elemMatch' => { qty: { '$gt' => 10, '$lte' => 20 } } })
findObservable = collection.find(elemMatch("instock", Document("""{ qty: { $gt: 10, $lte: 20 } }""")))
元素的组合满足标准
如果数组字段上的复合查询条件不使用$elemMatch
运算符,则查询将选择那些数组包含任何满足条件的元素组合的文档。
例如,以下查询匹配那些在instock
数组中嵌套的任何文档,其qty
字段大于10
,并且数组中的任何文档(但不必是相同的嵌入文档)的qty
字段小于或等于20
db.inventory.find( { "instock.qty": { $gt: 10, $lte: 20 } } )
将以下过滤器复制到 Compass 查询栏中,然后点击 查找
{ "instock.qty": { $gt: 10, $lte: 20 } }

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);
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();
cursor, err := coll.Find( context.TODO(), bson.D{ {"instock.qty", bson.D{ {"$gt", 10}, {"$lte", 20}, }}, })
findPublisher = collection.find(and(gt("instock.qty", 10), lte("instock.qty", 20)));
findIterable = collection.find(and(gt("instock.qty", 10), lte("instock.qty", 20)));
val findFlow = collection .find(and(gt("instock.qty", 10), lte("instock.qty", 20)))
cursor = db.inventory.find({"instock.qty": {"$gt": 10, "$lte": 20}})
const cursor = db.collection('inventory').find({ 'instock.qty': { $gt: 10, $lte: 20 } });
$cursor = $db->coll("inventory")->find( { "instock.qty" => { '$gt' => 10, '$lte' => 20 } } );
$cursor = $db->inventory->find(['instock.qty' => ['$gt' => 10, '$lte' => 20]]);
cursor = db.inventory.find({"instock.qty": {"$gt": 10, "$lte": 20}})
client[:inventory].find('instock.qty' => { '$gt' => 10, '$lte' => 20 })
findObservable = collection.find(and(gt("instock.qty", 10), lte("instock.qty", 20)))
以下示例查询那些instock
数组至少包含一个包含字段qty
等于5
的嵌入文档,并且至少包含一个包含字段warehouse
等于A
的嵌入文档(但不必是相同的嵌入文档)的文档
db.inventory.find( { "instock.qty": 5, "instock.warehouse": "A" } )
将以下过滤器复制到 Compass 查询栏中,然后点击 查找
{ "instock.qty": 5, "instock.warehouse": "A" }

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);
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();
cursor, err := coll.Find( context.TODO(), bson.D{ {"instock.qty", 5}, {"instock.warehouse", "A"}, })
findPublisher = collection.find(and(eq("instock.qty", 5), eq("instock.warehouse", "A")));
findIterable = collection.find(and(eq("instock.qty", 5), eq("instock.warehouse", "A")));
val findFlow = collection .find(and(eq("instock.qty", 5), eq("instock.warehouse", "A")))
cursor = db.inventory.find({"instock.qty": 5, "instock.warehouse": "A"})
const cursor = db.collection('inventory').find({ 'instock.qty': 5, 'instock.warehouse': 'A' });
$cursor = $db->coll("inventory")->find( { "instock.qty" => 5, "instock.warehouse" => "A" } );
$cursor = $db->inventory->find(['instock.qty' => 5, 'instock.warehouse' => 'A']);
cursor = db.inventory.find({"instock.qty": 5, "instock.warehouse": "A"})
client[:inventory].find('instock.qty' => 5, 'instock.warehouse' => 'A')
findObservable = collection.find(and(equal("instock.qty", 5), equal("instock.warehouse", "A")))
使用MongoDB Atlas查询文档数组
本节中的示例使用示例训练数据集。有关如何将示例数据集加载到您的MongoDB Atlas部署中的信息,请参阅加载示例数据。
要在MongoDB Atlas中查询文档数组,请按照以下步骤操作
在MongoDB Atlas UI中,转到您项目的集群页面。
如果尚未显示,请从导航栏的 组织菜单中选择包含您所需项目的组织。。
如果尚未显示,请从导航栏中的项目菜单中选择您的项目。
如果尚未显示,请点击侧边栏中的集群。
显示集群页面。
点击应用
此查询过滤器返回所有包含在sample_training.grades
集合中,且在scores
数组中存在子文档,其type
设置为exam
的文档。返回的完整文档包括整个scores
数组。有关修改返回数组的信息,请参阅在返回数组中投影特定数组元素。
其他查询教程
有关其他查询示例,请参阅