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 集合:

本页提供了使用 Collection.Find 对数组字段进行查询操作的示例。 MongoDB Go 驱动程序 中的函数 。

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

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

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

本页提供了使用 com.mongodb.client.MongoCollection.find 对数组字段进行查询操作的示例。 MongoDB Java 同步驱动程序中的方法。

提示

驱动程序提供了 com.mongodb.client.model.Filters 帮助器方法,以方便创建筛选器文档。本页上的示例使用这些方法创建筛选器文档。

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

本页提供了使用MongoCollection.find() MongoDB Kotlin 协程驱动程序中的方法。

提示

驱动程序提供了 com.mongodb.client.model.Filters 帮助器方法,以方便创建筛选器文档。本页上的示例使用这些方法创建筛选器文档。

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

本页提供的示例展示了使用 对数组字段执行查询操作motor.motor_asyncio.AsyncIOMotorCollection.find Motor 中的方法 驱动程序。

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

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

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

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

此页面上的示例使用的是 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", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
{ item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
{ item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
]);
[
{ "item": "journal", "qty": 25, "tags": ["blank", "red"], "dim_cm": [ 14, 21 ] },
{ "item": "notebook", "qty": 50, "tags": ["red", "blank"], "dim_cm": [ 14, 21 ] },
{ "item": "paper", "qty": 100, "tags": ["red", "blank", "plain"], "dim_cm": [ 14, 21 ] },
{ "item": "planner", "qty": 75, "tags": ["blank", "red"], "dim_cm": [ 22.85, 30 ] },
{ "item": "postcard", "qty": 45, "tags": ["blue"], "dim_cm": [ 10, 15.25 ] }
]

有关在 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"),
"qty", BCON_INT64 (25),
"tags", "[",
BCON_UTF8 ("blank"), BCON_UTF8 ("red"),
"]",
"dim_cm", "[",
BCON_INT64 (14), BCON_INT64 (21),
"]");
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),
"tags", "[",
BCON_UTF8 ("red"), BCON_UTF8 ("blank"),
"]",
"dim_cm", "[",
BCON_INT64 (14), BCON_INT64 (21),
"]");
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),
"tags", "[",
BCON_UTF8 ("red"), BCON_UTF8 ("blank"), BCON_UTF8 ("plain"),
"]",
"dim_cm", "[",
BCON_INT64 (14), BCON_INT64 (21),
"]");
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),
"tags", "[",
BCON_UTF8 ("blank"), BCON_UTF8 ("red"),
"]",
"dim_cm", "[",
BCON_DOUBLE (22.85), BCON_INT64 (30),
"]");
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),
"tags", "[",
BCON_UTF8 ("blue"),
"]",
"dim_cm", "[",
BCON_INT64 (10), BCON_DOUBLE (15.25),
"]");
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" },
{ "qty", 25 },
{ "tags", new BsonArray { "blank", "red" } },
{ "dim_cm", new BsonArray { 14, 21 } }
},
new BsonDocument
{
{ "item", "notebook" },
{ "qty", 50 },
{ "tags", new BsonArray { "red", "blank" } },
{ "dim_cm", new BsonArray { 14, 21 } }
},
new BsonDocument
{
{ "item", "paper" },
{ "qty", 100 },
{ "tags", new BsonArray { "red", "blank", "plain" } },
{ "dim_cm", new BsonArray { 14, 21 } }
},
new BsonDocument
{
{ "item", "planner" },
{ "qty", 75 },
{ "tags", new BsonArray { "blank", "red" } },
{ "dim_cm", new BsonArray { 22.85, 30 } }
},
new BsonDocument
{
{ "item", "postcard" },
{ "qty", 45 },
{ "tags", new BsonArray { "blue" } },
{ "dim_cm", new BsonArray { 10, 15.25 } }
}
};
collection.InsertMany(documents);
docs := []interface{}{
bson.D{
{"item", "journal"},
{"qty", 25},
{"tags", bson.A{"blank", "red"}},
{"dim_cm", bson.A{14, 21}},
},
bson.D{
{"item", "notebook"},
{"qty", 50},
{"tags", bson.A{"red", "blank"}},
{"dim_cm", bson.A{14, 21}},
},
bson.D{
{"item", "paper"},
{"qty", 100},
{"tags", bson.A{"red", "blank", "plain"}},
{"dim_cm", bson.A{14, 21}},
},
bson.D{
{"item", "planner"},
{"qty", 75},
{"tags", bson.A{"blank", "red"}},
{"dim_cm", bson.A{22.85, 30}},
},
bson.D{
{"item", "postcard"},
{"qty", 45},
{"tags", bson.A{"blue"}},
{"dim_cm", bson.A{10, 15.25}},
},
}
result, err := coll.InsertMany(context.TODO(), docs)
Publisher<Success> insertManyPublisher = collection.insertMany(asList(
Document.parse("{ item: 'journal', qty: 25, tags: ['blank', 'red'], dim_cm: [ 14, 21 ] }"),
Document.parse("{ item: 'notebook', qty: 50, tags: ['red', 'blank'], dim_cm: [ 14, 21 ] }"),
Document.parse("{ item: 'paper', qty: 100, tags: ['red', 'blank', 'plain'], dim_cm: [ 14, 21 ] }"),
Document.parse("{ item: 'planner', qty: 75, tags: ['blank', 'red'], dim_cm: [ 22.85, 30 ] }"),
Document.parse("{ item: 'postcard', qty: 45, tags: ['blue'], dim_cm: [ 10, 15.25 ] }")
));
collection.insertMany(asList(
Document.parse("{ item: 'journal', qty: 25, tags: ['blank', 'red'], dim_cm: [ 14, 21 ] }"),
Document.parse("{ item: 'notebook', qty: 50, tags: ['red', 'blank'], dim_cm: [ 14, 21 ] }"),
Document.parse("{ item: 'paper', qty: 100, tags: ['red', 'blank', 'plain'], dim_cm: [ 14, 21 ] }"),
Document.parse("{ item: 'planner', qty: 75, tags: ['blank', 'red'], dim_cm: [ 22.85, 30 ] }"),
Document.parse("{ item: 'postcard', qty: 45, tags: ['blue'], dim_cm: [ 10, 15.25 ] }")
));
collection.insertMany(
listOf(
Document("item", "journal")
.append("qty", 25)
.append("tags", listOf("blank", "red"))
.append("dim_cm", listOf(14, 21)),
Document("item", "notebook")
.append("qty", 50)
.append("tags", listOf("red", "blank"))
.append("dim_cm", listOf(14, 21)),
Document("item", "paper")
.append("qty", 100)
.append("tags", listOf("red", "blank", "plain"))
.append("dim_cm", listOf(14, 21)),
Document("item", "planner")
.append("qty", 75)
.append("tags", listOf("blank", "red"))
.append("dim_cm", listOf(22.85, 30)),
Document("item", "postcard")
.append("qty", 45)
.append("tags", listOf("blue"))
.append("dim_cm", listOf(10, 15.25)),
)
)
await db.inventory.insert_many(
[
{"item": "journal", "qty": 25, "tags": ["blank", "red"], "dim_cm": [14, 21]},
{"item": "notebook", "qty": 50, "tags": ["red", "blank"], "dim_cm": [14, 21]},
{
"item": "paper",
"qty": 100,
"tags": ["red", "blank", "plain"],
"dim_cm": [14, 21],
},
{"item": "planner", "qty": 75, "tags": ["blank", "red"], "dim_cm": [22.85, 30]},
{"item": "postcard", "qty": 45, "tags": ["blue"], "dim_cm": [10, 15.25]},
]
)
await db.collection('inventory').insertMany([
{
item: 'journal',
qty: 25,
tags: ['blank', 'red'],
dim_cm: [14, 21]
},
{
item: 'notebook',
qty: 50,
tags: ['red', 'blank'],
dim_cm: [14, 21]
},
{
item: 'paper',
qty: 100,
tags: ['red', 'blank', 'plain'],
dim_cm: [14, 21]
},
{
item: 'planner',
qty: 75,
tags: ['blank', 'red'],
dim_cm: [22.85, 30]
},
{
item: 'postcard',
qty: 45,
tags: ['blue'],
dim_cm: [10, 15.25]
}
]);
$db->coll("inventory")->insert_many(
[
{
item => "journal",
qty => 25,
tags => [ "blank", "red" ],
dim_cm => [ 14, 21 ]
},
{
item => "notebook",
qty => 50,
tags => [ "red", "blank" ],
dim_cm => [ 14, 21 ]
},
{
item => "paper",
qty => 100,
tags => [ "red", "blank", "plain" ],
dim_cm => [ 14, 21 ]
},
{
item => "planner",
qty => 75,
tags => [ "blank", "red" ],
dim_cm => [ 22.85, 30 ]
},
{
item => "postcard",
qty => 45,
tags => ["blue"],
dim_cm => [ 10, 15.25 ]
}
]
);
$insertManyResult = $db->inventory->insertMany([
[
'item' => 'journal',
'qty' => 25,
'tags' => ['blank', 'red'],
'dim_cm' => [14, 21],
],
[
'item' => 'notebook',
'qty' => 50,
'tags' => ['red', 'blank'],
'dim_cm' => [14, 21],
],
[
'item' => 'paper',
'qty' => 100,
'tags' => ['red', 'blank', 'plain'],
'dim_cm' => [14, 21],
],
[
'item' => 'planner',
'qty' => 75,
'tags' => ['blank', 'red'],
'dim_cm' => [22.85, 30],
],
[
'item' => 'postcard',
'qty' => 45,
'tags' => ['blue'],
'dim_cm' => [10, 15.25],
],
]);
db.inventory.insert_many(
[
{"item": "journal", "qty": 25, "tags": ["blank", "red"], "dim_cm": [14, 21]},
{"item": "notebook", "qty": 50, "tags": ["red", "blank"], "dim_cm": [14, 21]},
{
"item": "paper",
"qty": 100,
"tags": ["red", "blank", "plain"],
"dim_cm": [14, 21],
},
{"item": "planner", "qty": 75, "tags": ["blank", "red"], "dim_cm": [22.85, 30]},
{"item": "postcard", "qty": 45, "tags": ["blue"], "dim_cm": [10, 15.25]},
]
)
client[:inventory].insert_many([{ item: 'journal',
qty: 25,
tags: ['blank', 'red'],
dim_cm: [ 14, 21 ] },
{ item: 'notebook',
qty: 50,
tags: ['red', 'blank'],
dim_cm: [ 14, 21 ] },
{ item: 'paper',
qty: 100,
tags: ['red', 'blank', 'plain'],
dim_cm: [ 14, 21 ] },
{ item: 'planner',
qty: 75,
tags: ['blank', 'red'],
dim_cm: [ 22.85, 30 ] },
{ item: 'postcard',
qty: 45,
tags: ['blue'],
dim_cm: [ 10, 15.25 ] }
])
collection.insertMany(Seq(
Document("""{ item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] }"""),
Document("""{ item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] }"""),
Document("""{ item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] }"""),
Document("""{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] }"""),
Document("""{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }""")
)).execute()

要对数组指定相等条件,请使用查询文档 { <field>: <value> },其中 <value> 是要匹配的精确数组,包括元素的顺序。

要对数组指定相等条件,请使用查询文档 { <field>: <value> },其中 <value> 是要匹配的精确数组,包括元素的顺序。

要对数组指定相等条件,请使用查询文档 { <field>: <value> },其中 <value> 是要匹配的精确数组,包括元素的顺序。

要对数组指定相等条件,请使用Eq方法,其中<value>是要匹配的精确数组,包括元素的顺序:

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

要对数组指定相等条件,请使用查询文档 eq( <field>, <value>),其中 <value> 是要匹配的精确数组,包括元素的顺序。

要对数组指定相等条件,请使用查询文档 eq( <field>, <value>),其中 <value> 是要匹配的精确数组,包括元素的顺序。

要对数组指定相等条件,请使用查询文档 { <field>: <value> },其中 <value> 是要匹配的精确数组,包括元素的顺序。

要对数组指定相等条件,请使用查询文档 { <field>: <value> },其中 <value> 是要匹配的精确数组,包括元素的顺序。

要对数组指定相等条件,请使用查询文档 { <field> => <value> },其中 <value> 是要匹配的精确数组,包括元素的顺序。

要对数组指定相等条件,请使用查询文档 [ <field> => <value> ],其中 <value> 是要匹配的精确数组,包括元素的顺序。

要对数组指定相等条件,请使用查询文档 { <field>: <value> },其中 <value> 是要匹配的精确数组,包括元素的顺序。

要对数组指定相等条件,请使用查询文档 { <field> => <value> },其中 <value> 是要匹配的精确数组,包括元素的顺序。

要对数组指定相等条件,请使用查询文档 equal( <field>, <value> ),其中 <value> 是要匹配的精确数组,包括元素的顺序。

以下示例查询字段 tags 值是一个数组且恰好有两个元素 "red""blank"(按指定顺序)的所有文档:

db.inventory.find( { tags: ["red", "blank"] } )

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

{ tags: ["red", "blank"] }
查询数组精确匹配
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;
collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW (
"tags", "[",
BCON_UTF8 ("red"), BCON_UTF8 ("blank"),
"]");
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);
var filter = Builders<BsonDocument>.Filter.Eq("tags", new[] { "red", "blank" });
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{{"tags", bson.A{"red", "blank"}}},
)
FindPublisher<Document> findPublisher = collection.find(eq("tags", asList("red", "blank")));
FindIterable<Document> findIterable = collection.find(eq("tags", asList("red", "blank")));
val findFlow = collection
.find(eq("tags", listOf("red", "blank")))
cursor = db.inventory.find({"tags": ["red", "blank"]})
const cursor = db.collection('inventory').find({
tags: ['red', 'blank']
});
$cursor = $db->coll("inventory")->find( { tags => [ "red", "blank" ] } );
$cursor = $db->inventory->find(['tags' => ['red', 'blank']]);
cursor = db.inventory.find({"tags": ["red", "blank"]})
client[:inventory].find(tags: ['red', 'blank'])
var findObservable = collection.find(equal("tags", Seq("red", "blank")))

相反,如果想查找同时包含 "red""blank" 元素的数组,而不考虑顺序或数组中的其他元素,则请使用 $all 运算符:

db.inventory.find( { tags: { $all: ["red", "blank"] } } )

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

{ tags: { $all: ["red", "blank"] } }
匹配所有条件的查询数组
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;
collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW (
"tags", "{",
"$all", "[",
BCON_UTF8 ("red"), BCON_UTF8 ("blank"),
"]",
"}");
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);
var filter = Builders<BsonDocument>.Filter.All("tags", new[] { "red", "blank" });
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"tags", bson.D{{"$all", bson.A{"red", "blank"}}}},
})
findPublisher = collection.find(all("tags", asList("red", "blank")));
findIterable = collection.find(all("tags", asList("red", "blank")));
val findFlow = collection
.find(all("tags", listOf("red", "blank")))
cursor = db.inventory.find({"tags": {"$all": ["red", "blank"]}})
const cursor = db.collection('inventory').find({
tags: { $all: ['red', 'blank'] }
});
$cursor = $db->coll("inventory")->find( { tags => { '$all' => [ "red", "blank" ] } } );
$cursor = $db->inventory->find(['tags' => ['$all' => ['red', 'blank']]]);
cursor = db.inventory.find({"tags": {"$all": ["red", "blank"]}})
client[:inventory].find(tags: { '$all' => ['red', 'blank'] })
findObservable = collection.find(all("tags", "red", "blank"))

要查询数组字段是否至少包含一个具有指定值的元素,请使用筛选器 { <field>: <value> },其中的 <value> 是元素值。

要查询数组字段是否至少包含一个具有指定值的元素,请使用筛选器 { <field>: <value> },其中的 <value> 是元素值。

要查询数组字段是否至少包含一个具有指定值的元素,请使用以下公式方法,其中<value>是要匹配的元素值:

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

要查询数组字段是否至少包含一个具有指定值的元素,请使用筛选器eq( <field>, <value>) ,其中 value 是元素值。

要查询数组字段是否至少包含一个具有指定值的元素,请使用筛选器 eq( <field>, <value>),其中的 <value> 是元素值。

要查询数组字段是否至少包含一个具有指定值的元素,请使用筛选器 { <field>: <value> },其中的 <value> 是元素值。

要查询数组字段是否至少包含一个具有指定值的元素,请使用筛选器 { <field>: <value> },其中的 <value> 是元素值。

要查询数组字段是否至少包含一个具有指定值的元素,请使用筛选器

{ <field> => <value> } 其中 value 是元素值。

要查询数组字段是否至少包含一个具有指定值的元素,请使用筛选器 [ <field> => <value> ],其中的 <value> 是元素值。

要查询数组字段是否至少包含一个具有指定值的元素,请使用筛选器 { <field>: <value> },其中的 <value> 是元素值。

要查询数组字段是否至少包含一个具有指定值的元素,请使用筛选器 { <field> => <value> },其中的 <value> 是元素值。

要查询数组字段是否至少包含一个具有指定值的元素,请使用筛选器 equal( <field>, <value> ),其中的 <value> 是元素值。

以下示例将查询所有文档,其中 tags 为包含字符串 "red" 以作为其元素之一的数组:

db.inventory.find( { tags: "red" } )

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

{ tags: "red" }
匹配多个条件的查询数组
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;
collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW ("tags", BCON_UTF8 ("red"));
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);
var filter = Builders<BsonDocument>.Filter.Eq("tags", "red");
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"tags", "red"},
})
findPublisher = collection.find(eq("tags", "red"));
findIterable = collection.find(eq("tags", "red"));
val findFlow = collection
.find(eq("tags", "red"))
cursor = db.inventory.find({"tags": "red"})
const cursor = db.collection('inventory').find({
tags: 'red'
});
$cursor = $db->coll("inventory")->find( { tags => "red" } );
$cursor = $db->inventory->find(['tags' => 'red']);
cursor = db.inventory.find({"tags": "red"})
client[:inventory].find(tags: 'red')
findObservable = collection.find(equal("tags", "red"))

要对数组字段中的元素指定条件,请在查询过滤器文档中使用查询运算符

{ <array field>: { <operator1>: <value1>, ... } }

要对数组字段中的元素指定条件,请在查询过滤器文档中使用查询运算符

{ <array field>: { <operator1>: <value1>, ... } }

要对数组字段中的元素指定条件,请在查询过滤器文档中使用查询运算符

{ <array field>: { <operator1>: <value1>, ... } }

要对数组字段中的元素指定条件,请在查询筛选器文档中使用查询运算符。例如:

var builder = Builders<BsonDocument>.Filter;
builder.And(builder.Eq(<array field>, <value1>), builder.Lt(<array field>, <value2>));

要对数组字段中的元素指定条件,请在查询筛选器文档中使用查询运算符。例如:

and(gte(<array field>, <value1>), lt(<array field>, <value2>) ...)

要对数组字段中的元素指定条件,请在查询筛选器文档中使用查询运算符。例如:

and(gte(<array field>, <value1>), lt(<array field>, <value2>) ...)

要对数组字段中的元素指定条件,请在查询筛选器文档中使用查询运算符。例如:

and(gte(<array field>, <value1>), lt(<array field>, <value2>) ...)

要对数组字段中的元素指定条件,请在查询过滤器文档中使用查询运算符

{ <array field>: { <operator1>: <value1>, ... } }

要对数组字段中的元素指定条件,请在查询过滤器文档中使用查询运算符

{ <array field> => { <operator1> => <value1>, ... } }

要对数组字段中的元素指定条件,请在查询过滤器文档中使用查询运算符

[ <array field> => [ <operator1> => <value1>, ... ] ]

要对数组字段中的元素指定条件,请在查询过滤器文档中使用查询运算符

{ <array field>: { <operator1>: <value1>, ... } }

要对数组字段中的元素指定条件,请在查询过滤器文档中使用查询运算符

{ <array field> => { <operator1> => <value1>, ... } }

要对数组字段中的元素指定条件,请在查询过滤器文档中使用查询运算符

and(gte(<array field>, <value1>), lt(<array field>, <value2>) ...)

例如,以下操作将查询所有文档,其中数组 dim_cm 至少包含一个其值大于 25 的元素。

db.inventory.find( { dim_cm: { $gt: 25 } } )

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

{ dim_cm: { $gt: 25 } }
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;
collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW (
"dim_cm", "{",
"$gt", BCON_INT64 (25),
"}");
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);
var filter = Builders<BsonDocument>.Filter.Gt("dim_cm", 25);
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"dim_cm", bson.D{
{"$gt", 25},
}},
})
findPublisher = collection.find(gt("dim_cm", 25));
findIterable = collection.find(gt("dim_cm", 25));
val findFlow = collection
.find(gt("dim_cm", 25))
cursor = db.inventory.find({"dim_cm": {"$gt": 25}})
const cursor = db.collection('inventory').find({
dim_cm: { $gt: 25 }
});
$cursor = $db->coll("inventory")->find( { "dim_cm" => { '$gt' => 25 } } );
$cursor = $db->inventory->find(['dim_cm' => ['$gt' => 25]]);
cursor = db.inventory.find({"dim_cm": {"$gt": 25}})
client[:inventory].find(dim_cm: { '$gt' => 25 })
findObservable = collection.find(gt("dim_cm", 25))

在用复合条件查询数组中的元素时,您可以设置查询语句,使单个数组元素满足查询条件或是任意数组元素的组合满足查询条件。

以下示例将查询特定文档,其中 dim_cm 数组包含以某种组合形式可满足查询条件的元素;例如,一个元素可满足大于 15 的条件,而另一元素可满足小于 20 的条件,或是单个元素可同时满足这两个条件:

db.inventory.find( { dim_cm: { $gt: 15, $lt: 20 } } )

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

{ dim_cm: { $gt: 15, $lt: 20 } }
使用复合筛选器查询数组
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;
collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW (
"dim_cm", "{",
"$gt", BCON_INT64 (15),
"$lt", BCON_INT64 (20),
"}");
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);
var builder = Builders<BsonDocument>.Filter;
var filter = builder.And(builder.Gt("dim_cm", 15), builder.Lt("dim_cm", 20));
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"dim_cm", bson.D{
{"$gt", 15},
{"$lt", 20},
}},
})
findPublisher = collection.find(and(gt("dim_cm", 15), lt("dim_cm", 20)));
findIterable = collection.find(and(gt("dim_cm", 15), lt("dim_cm", 20)));
val findFlow = collection
.find(and(gt("dim_cm", 15), lt("dim_cm", 20)))
cursor = db.inventory.find({"dim_cm": {"$gt": 15, "$lt": 20}})
const cursor = db.collection('inventory').find({
dim_cm: { $gt: 15, $lt: 20 }
});
$cursor = $db->coll("inventory")->find(
{ "dim_cm" => { '$gt' => 15, '$lt' => 20 } }
);
$cursor = $db->inventory->find([
'dim_cm' => [
'$gt' => 15,
'$lt' => 20,
],
]);
cursor = db.inventory.find({"dim_cm": {"$gt": 15, "$lt": 20}})
client[:inventory].find(dim_cm: { '$gt' => 15,
'$lt' => 20 })
findObservable = collection.find(and(gt("dim_cm", 15), lt("dim_cm", 20)))

使用 $elemMatch 运算符为数组的元素指定多个条件,以使至少一个数组元素满足所有指定的条件。

以下示例将查询特定文档,其中 dim_cm 数组至少包含一个大于 ($gt) 22 且小于 ($lt) 30 的元素:

db.inventory.find( { dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } } )

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

{ dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } }
按多个条件查询数组
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;
collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW (
"dim_cm", "{",
"$elemMatch", "{",
"$gt", BCON_INT64 (22),
"$lt", BCON_INT64 (30),
"}",
"}");
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);
var filter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>("dim_cm", new BsonDocument { { "$gt", 22 }, { "$lt", 30 } });
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"dim_cm", bson.D{
{"$elemMatch", bson.D{
{"$gt", 22},
{"$lt", 30},
}},
}},
})
findPublisher = collection.find(elemMatch("dim_cm", Document.parse("{ $gt: 22, $lt: 30 }")));
findIterable = collection.find(elemMatch("dim_cm", Document.parse("{ $gt: 22, $lt: 30 }")));
val findFlow = collection
.find(elemMatch("dim_cm", Document.parse("{ \$gt: 22, \$lt: 30 }")))
cursor = db.inventory.find({"dim_cm": {"$elemMatch": {"$gt": 22, "$lt": 30}}})
const cursor = db.collection('inventory').find({
dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } }
});
$cursor = $db->coll("inventory")->find(
{ dim_cm => { '$elemMatch' => { '$gt' => 22, '$lt' => 30 } } }
);
$cursor = $db->inventory->find([
'dim_cm' => [
'$elemMatch' => [
'$gt' => 22,
'$lt' => 30,
],
],
]);
cursor = db.inventory.find({"dim_cm": {"$elemMatch": {"$gt": 22, "$lt": 30}}})
client[:inventory].find(dim_cm: { '$elemMatch' => { '$gt' => 22,
'$lt' => 30 } })
findObservable = collection.find(elemMatch("dim_cm", Document("$gt" -> 22, "$lt" -> 30)))

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

注意

使用点表示法查询时,字段和嵌套字段必须放在引号内。

以下示例将查询所有文档,其中数组 dim_cm 中的第二个元素大于 25

db.inventory.find( { "dim_cm.1": { $gt: 25 } } )

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

{ "dim_cm.1": { $gt: 25 } }
按索引查询数组
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;
collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW (
"dim_cm.1", "{",
"$gt", BCON_INT64 (25),
"}");
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);
var filter = Builders<BsonDocument>.Filter.Gt("dim_cm.1", 25);
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"dim_cm.1", bson.D{
{"$gt", 25},
}},
})
findPublisher = collection.find(elemMatch("dim_cm", Document.parse("{ $gt: 22, $lt: 30 }")));
findIterable = collection.find(gt("dim_cm.1", 25));
val findFlow = collection
.find(gt("dim_cm.1", 25))
cursor = db.inventory.find({"dim_cm.1": {"$gt": 25}})
const cursor = db.collection('inventory').find({
'dim_cm.1': { $gt: 25 }
});
$cursor = $db->coll("inventory")->find( { "dim_cm.1" => { '$gt' => 25 } } );
$cursor = $db->inventory->find(['dim_cm.1' => ['$gt' => 25]]);
cursor = db.inventory.find({"dim_cm.1": {"$gt": 25}})
client[:inventory].find('dim_cm.1' => { '$gt' => 25 })
findObservable = collection.find(gt("dim_cm.1", 25))

使用 $size 操作符以便按元素个数来查询数组。例如,以下示例会选择数组 tags 有 3 个元素的文档。

db.inventory.find( { "tags": { $size: 3 } } )

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

{ "tags": { $size: 3 } }
mongoc_collection_t *collection;
bson_t *filter;
mongoc_cursor_t *cursor;
collection = mongoc_database_get_collection (db, "inventory");
filter = BCON_NEW (
"tags", "{",
"$size", BCON_INT64 (3),
"}");
cursor = mongoc_collection_find_with_opts (collection, filter, NULL, NULL);

此外,请务必根据需要调用以下方法来清理所有打开的资源:

var filter = Builders<BsonDocument>.Filter.Size("tags", 3);
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"tags", bson.D{
{"$size", 3},
}},
})
findPublisher = collection.find(size("tags", 3));
findIterable = collection.find(size("tags", 3));
val findFlow = collection
.find(size("tags", 3))
cursor = db.inventory.find({"tags": {"$size": 3}})
const cursor = db.collection('inventory').find({
tags: { $size: 3 }
});
$cursor = $db->coll("inventory")->find( { tags => { '$size' => 3 } } );
$cursor = $db->inventory->find(['tags' => ['$size' => 3]]);
cursor = db.inventory.find({"tags": {"$size": 3}})
client[:inventory].find(tags: { '$size' => 3 })
findObservable = collection.find(size("tags", 3))

本部分的示例使用的是示例电影数据集。要了解如何将示例数据集加载到您的 MongoDB Atlas 部署中,请参阅加载示例数据

要在 MongoDB Atlas 中查询数组,请按照以下步骤操作:

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

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

  3. 如果 Clusters(数据库部署)页面尚未出现,请单击侧边栏中的 Database(数据库)。

    此时会显示“集群”页面。

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

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

  3. 选择 movies 集合。

3

要查询包含数组的文档,请指定查询筛选器文档。 查询筛选器文档使用查询操作符来指定搜索条件。 使用以下示例文档来查询sample_mflix.movies 集合中的大量字段。

要应用查询过滤器,请将示例文档复制到 Filter(过滤器)搜索栏,然后单击 Apply(应用)。

要对数组指定相等条件,请使用查询文档 { <field>: <value> },其中 <value> 是要匹配的精确数组,包括元素的顺序。以下示例查找具有 genres 字段的文档,该字段包含按指定顺序排序的 ["Action", "Comedy"] 数组:

{ genres: ["Action", "Comedy"] }

要查找同时包含 ActionComedy 这两个元素的数组,而不考虑顺序或数组中的其他元素,请使用 $all 操作符:

{ genres: { $all: ["Action", "Comedy"] } }

要查询数组字段是否至少包含一个具有指定值的元素,请使用筛选器{ <field>: <value> } ,其中<value>是元素值。

以下示例查询 genres 字段包含string Short 作为其元素之一的所有文档:

{ genres: "Short" }

要对数组字段中的元素指定条件,请在查询过滤器文档中使用查询运算符

{ <array field>: { <operator1>: <value1>, ... } }

例如,以下操作使用$nin操作符查询genres字段不包含Drama的所有文档。

{ genres: { $nin: ["Drama"] } }

在用复合条件查询数组中的元素时,您可以设置查询语句,使单个数组元素满足查询条件或是任意数组元素的组合满足查询条件。

下面的示例查询的是 cast 数组包含的元素在某种组合上满足查询条件的文档。例如,以下过滤器使用 $regex$eq 操作符返回单个数组元素以 Olsen 结尾且另一个元素等于 Mary-Kate Olsen 的文档,或者返回同时满足这两个条件的单个元素:

{ cast: { $regex: "Olsen$", $eq: "Mary-Kate Olsen" } }

此查询筛选器返回演员阵容中包含Mary-Kate Olsen的电影,以及演员阵容中同时包含Mary-Kate OlsenAshley Olsen的电影。

使用 $elemMatch 运算符为数组的元素指定多个条件,以使至少一个数组元素满足所有指定的条件。

以下示例使用$elemMatch$ne操作符查询文档,其中languages数组至少包含一个既不是null又不等于English的元素。

{ languages: { $elemMatch: { $ne: null, $ne: "English" } } }

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

注意

使用点表示法查询时,字段和嵌套字段必须放在引号内。

以下示例使用 $ne 操作符查询 countries 数组中第一个元素不等于 USA 的所有文档:

{ "countries.0": { $ne: "USA" }

使用 $size 操作符以便按元素个数来查询数组。例如,以下示例会选择数组 genres 有 3 个元素的文档。

{ genres: { $size: 3 } }

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

后退

嵌入式文档