Docs 菜单
Docs 主页
/
MongoDB Manual
/ /

查询嵌入式文档数组

在此页面上

  • 查询嵌套在数组中的文档
  • 在文档数组中的字段上指定查询条件
  • 为文档数组指定多个条件
  • 使用 MongoDB Atlas 查询文档数组
  • 其他查询教程

您可以使用以下方法查询MongoDB中的文档:

  • 您的编程语言的驱动程序。

  • MongoDB Atlas 用户界面。要了解更多信息,请参阅使用 MongoDB Atlas 查询文档阵列

  • MongoDB Compass。


➤ 使用右上角的 Select your language(选择语言)下拉菜单,设置以下示例的语言或选择 MongoDB Compass。


此页面中的示例展示了在 mongosh 中使用 db.collection.find() 方法对嵌套文档数组执行查询操作。

此页面上的示例使用的是 inventory 集合。连接到 MongoDB 实例中的测试数据库,然后创建 inventory 集合:

本页面中的示例展示了使用 MongoDB Compass 对嵌套文档数组执行查询操作。

此页面上的示例使用的是 inventory 集合。连接到 MongoDB 实例中的测试数据库,然后创建 inventory 集合:

本页提供了使用 mongoc_collection_find_with_opts 对嵌套文档大量进行查询操作的示例。

此页面上的示例使用的是 inventory 集合。连接到 MongoDB 实例中的测试数据库,然后创建 inventory 集合:

本页提供了使用 MongoDB C# 驱动程序中的 MongoCollection.Find() 方法对嵌入/嵌套文档进行查询操作的示例。

此页面上的示例使用的是 inventory 集合。连接到 MongoDB 实例中的测试数据库,然后创建 inventory 集合:

本页面中的示例展示了使用 MongoDB Go Driver 中的 Collection.Find 函数对嵌套文档数组进行查询操作。

此页面上的示例使用的是 inventory 集合。连接到 MongoDB 实例中的测试数据库,然后创建 inventory 集合:

本页面中的示例展示了使用 MongoDB Java Reactive Streams 驱动程序中的 com.mongodb.reactivestreams.client.MongoCollection.find 方法对嵌套文档数组执行查询操作。

此页面上的示例使用的是 inventory 集合。连接到 MongoDB 实例中的测试数据库,然后创建 inventory 集合:

此页面中的示例展示了使用 MongoDB Java 同步驱动程序中的 com.mongodb.client.MongoCollection.find 方法对嵌套文档数组执行的查询操作。

提示

此驱动程序提供了 com.mongodb.client.model.Filters 辅助方法,以便于创建过滤器文档。此页面中的示例使用这些方法创建过滤器文档。

此页面上的示例使用的是 inventory 集合。连接到 MongoDB 实例中的测试数据库,然后创建 inventory 集合:

本页提供的示例展示了使用 MongoCollection.find() 对嵌套文档大量进行查询操作。MongoDB Kotlin协程驱动程序中的方法。

提示

此驱动程序提供了 com.mongodb.client.model.Filters 辅助方法,以便于创建过滤器文档。此页面中的示例使用这些方法创建过滤器文档。

此页面上的示例使用的是 inventory 集合。连接到 MongoDB 实例中的测试数据库,然后创建 inventory 集合:

此页面中的示例展示了使用 Motor 驱动程序中的 motor.motor_asyncio.AsyncIOMotorCollection.find 方法对嵌套文档数组执行查询操作。

此页面上的示例使用的是 inventory 集合。连接到 MongoDB 实例中的测试数据库,然后创建 inventory 集合:

本页面提供的示例展示使用 Collection.find() 方法在 MongoDB Node.js 驱动程序 中对嵌套文档的数组执行查询操作。

此页面上的示例使用的是 inventory 集合。连接到 MongoDB 实例中的测试数据库,然后创建 inventory 集合:

本页面提供了使用 MongoDB Perl 驱动程序中的 MongoDB::Collection::find() 方法对嵌套文档数组进行查询操作的示例。

此页面上的示例使用的是 inventory 集合。连接到 MongoDB 实例中的测试数据库,然后创建 inventory 集合:

此页面中的示例展示了使用 MongoDB PHP 库中的 MongoDB\\Collection::find() 方法对嵌套文档的数组执行查询操作。

此页面上的示例使用的是 inventory 集合。连接到 MongoDB 实例中的测试数据库,然后创建 inventory 集合:

本页提供的示例展示了使用 对嵌套文档大量执行查询操作pymongo.collection.Collection.find PyMongo Python驾驶员中的方法。

此页面上的示例使用的是 inventory 集合。连接到 MongoDB 实例中的测试数据库,然后创建 inventory 集合:

本页提供了使用 MongoDB Ruby 驱动程序中的 Mongo::Collection#find() 方法对嵌套文档数组进行查询操作的示例。

此页面上的示例使用的是 inventory 集合。连接到 MongoDB 实例中的测试数据库,然后创建 inventory 集合:

本页面提供的示例展示使用 Collection.find() 方法在 MongoDB Scala 驱动程序中执行查询操作。

此页面上的示例使用的是 inventory 集合。连接到 MongoDB 实例中的测试数据库,然后创建 inventory 集合:

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 查询栏中,然后单击 Find

{ "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 查询栏中,然后单击 Find

{ '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))

使用点符号,可以在数组的特定索引或位置为文档中的字段指定查询条件。该数组使用从零开始的索引。

注意

使用点符号查询时,字段和索引必须位于引号内。

以下示例选择所有满足如下条件的文档——instock 数组的第一个元素是包含值小于或等于 20qty 字段的文档:

db.inventory.find( { 'instock.0.qty': { $lte: 20 } } )

将以下过滤器复制到 Compass 查询栏中,然后单击 Find

{ '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 操作符在大量嵌入式文档中指定多个条件,以使至少一个嵌入式文档满足所有指定条件。

以下示例查询满足如下条件的文档——instock 数组至少有一份嵌入式文档,该文档同时包含等于 5 的字段 qty 和等于 A 的字段 warehouse

db.inventory.find( { "instock": { $elemMatch: { qty: 5, warehouse: "A" } } } )

将以下过滤器复制到 Compass 查询栏中,然后单击 Find

{ "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")))

以下示例将查询 instock 数组至少包含一个嵌入文档,且该文档包含大于 qty 且小于或等于 20 的字段 10

db.inventory.find( { "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } } )

将以下过滤器复制到 Compass 查询栏中,然后单击 Find

{ "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 查询栏中,然后单击 Find

{ "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 数组至少有一个包含等于 5 的字段 qty 的嵌入式文档,以及至少一个包含等于 A 的字段 warehouse 的嵌入式文档(但不一定是同一个嵌入式文档):

db.inventory.find( { "instock.qty": 5, "instock.warehouse": "A" } )

将以下过滤器复制到 Compass 查询栏中,然后单击 Find

{ "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 中查询文档数组,请按照以下步骤操作:

1
  1. 如果尚未显示,请从导航栏上的 Organizations 菜单中选择包含所需项目的组织。

  2. 如果尚未显示,请从导航栏的 Projects 菜单中选择您的项目。

  3. 如果尚未显示,请单击侧边栏中的Clusters

    会显示集群页面。

2
  1. 对于包含样本数据的集群,单击Browse Collections

  2. 在左侧导航窗格中,选择 sample_training 数据库。

  3. 选择 grades 集合。

3

Filter 字段中指定查询筛选器文档。查询筛选器文档使用查询运算符来指定搜索条件。

将以下查询筛选器文档复制到 Filter 搜索栏:

{"scores.type": "exam"}
4

此查询过滤器返回 sample_training.grades 集合中包含 scores 数组中子文档的所有文档,其中 type 设置为 exam。将返回包括整个 scores 数组在内的完整文档。有关修改返回数组的更多信息,请参阅已返回数组中特定于项目的数组元素。

有关其他查询示例,请参阅:

后退

数组