You can query arrays in MongoDB using the following methods:您可以使用以下方法在MongoDB中查询数组:
Your programming language's driver.你的编程语言的驱动程序。The MongoDB Atlas UI. To learn more, see Query an Array 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 array fields 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 array fields 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 array fields 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 array fields 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 array fields 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 array fields 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 array fields 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 array fields 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 array fields 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 array fields 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:inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:
PHP
This page provides examples of query operations on array fields using the 本页提供了使用MongoDB PHP库中的MongoDB\\Collection::find() method in the MongoDB PHP Library.MongoDB\\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集合:
Python
This page provides examples of query operations on array fields using the 本页提供了使用PyMongo Python驱动程序中的pymongo.collection.Collection.find method in the PyMongo Python driver.pymongo.collection.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集合:
Ruby
This page provides examples of query operations on array fields using the Mongo::Collection#find() method in the MongoDB Ruby Driver.本页提供了使用MongoDB Ruby驱动程序中的Mongo::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集合:
scala
This page provides examples of query operations on array fields using the 本页提供了使用MongoDB Scala驱动程序中的collection.find() method in the MongoDB Scala 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:inventory集合。连接到MongoDB实例中的测试数据库,然后创建inventory集合:
MongoDB Shell
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 ] }
]);Compass
[
{ "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 ] }
]
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"),
"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);
}C#
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);Go
docs := []any{
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)Java(Async)
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 ] }")
));Java(Sync)
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 ] }")
));Kotlin(Coroutine)
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)),
)
)Motor
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]},
]
)Node.js
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]
}
]);PHP
$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],
],
]);Python
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]},
]
)Ruby
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 ] }
])scala
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()Match an Array匹配数组
MongoDB Shell
To specify equality condition on an array, use the query document 要指定数组的相等条件,请使用查询文档{ <field>: <value> } where <value> is the exact array to match, including the order of the elements.{ <field>: <value> },其中<value>是要匹配的确切数组,包括元素的顺序。
Compass
To specify equality condition on an array, use the query document 要指定数组的相等条件,请使用查询文档{ <field>: <value> } where <value> is the exact array to match, including the order of the elements.{ <field>: <value> },其中<value>是要匹配的确切数组,包括元素的顺序。
C
To specify equality condition on an array, use the query document 要指定数组的相等条件,请使用查询文档{ <field>: <value> } where <value> is the exact array to match, including the order of the elements.{ <field>: <value> },其中<value>是要匹配的确切数组,包括元素的顺序。
C#
To specify equality condition on an array, construct a filter using the Eq method, where 要指定数组的相等条件,请使用<value> is the exact array to match, including the order of the elements:Eq方法构造一个筛选器,其中<value>是要匹配的精确数组,包括元素的顺序:
Builders<BsonDocument>.Filter.Eq(<field>, <value>)Java(Async)
To specify equality condition on an array, use the query document 要指定数组的相等条件,请使用查询文档eq( <field>, <value>) where <value> is the exact array to match, including the order of the elements.eq( <field>, <value>),其中<value>是要匹配的确切数组,包括元素的顺序。
Java(Sync)
To specify equality condition on an array, use the query document 要指定数组的相等条件,请使用查询文档eq( <field>, <value>) where <value> is the exact array to match, including the order of the elements.eq( <field>, <value>),其中<value>是要匹配的确切数组,包括元素的顺序。
Motor
To specify equality condition on an array, use the query document 要指定数组的相等条件,请使用查询文档{ <field>: <value> } where <value> is the exact array to match, including the order of the elements.{ <field>: <value> },其中<value>是要匹配的确切数组,包括元素的顺序。
Node.js
To specify equality condition on an array, use the query document 要指定数组的相等条件,请使用查询文档{ <field>: <value> } where <value> is the exact array to match, including the order of the elements.{ <field>: <value> },其中<value>是要匹配的确切数组,包括元素的顺序。
PHP
To specify equality condition on an array, use the query document 要指定数组的相等条件,请使用查询文档[ <field> => <value> ] where <value> is the exact array to match, including the order of the elements.[ <field> => <value> ],其中<value>是要匹配的确切数组,包括元素的顺序。
Python
To specify equality condition on an array, use the query document 要指定数组的相等条件,请使用查询文档{ <field>: <value> } where <value> is the exact array to match, including the order of the elements.{ <field>: <value> },其中<value>是要匹配的确切数组,包括元素的顺序。
Ruby
To specify equality condition on an array, use the query document 要指定数组的相等条件,请使用查询文档{ <field> => <value> } where <value> is the exact array to match, including the order of the elements.{ <field> => <value> },其中<value>是要匹配的确切数组,包括元素的顺序。
scala
To specify equality condition on an array, use the query document 要指定数组的相等条件,请使用查询文档equal( <field>, <value> ) where <value> is the exact array to match, including the order of the elements.equal( <field>, <value> ),其中<value>是要匹配的确切数组,包括元素的顺序。
The following example queries for all documents where the field 以下示例查询所有字段tags value is an array with exactly two elements, "red" and "blank", in the specified order:tags值为数组的文档,数组中按指定顺序恰好有两个元素"red"和"blank":
MongoDB Shell
db.inventory.find( { tags: ["red", "blank"] } )Compass
Copy the following filter into the Compass query bar and click Find:将以下筛选器复制到Compass查询栏中,然后单击“查找”:
{ tags: ["red", "blank"] }

C
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);C#
var filter = Builders<BsonDocument>.Filter.Eq("tags", new[] { "red", "blank" });
var result = collection.Find(filter).ToList();Go
cursor, err := coll.Find(
context.TODO(),
bson.D{{"tags", bson.A{"red", "blank"}}},
)Java(Async)
FindPublisher<Document> findPublisher = collection.find(eq("tags", asList("red", "blank")));Java(Sync)
FindIterable<Document> findIterable = collection.find(eq("tags", asList("red", "blank")));Kotlin(Coroutine)
val findFlow = collection
.find(eq("tags", listOf("red", "blank")))Motor
cursor = db.inventory.find({"tags": ["red", "blank"]})Node.js
const cursor = db.collection('inventory').find({
tags: ['red', 'blank']
});PHP
$cursor = $db->inventory->find(['tags' => ['red', 'blank']]);Python
cursor = db.inventory.find({"tags": ["red", "blank"]})Ruby
client[:inventory].find(tags: ['red', 'blank'])scala
var findObservable = collection.find(equal("tags", Seq("red", "blank")))If, instead, you wish to find an array that contains both the elements 相反,如果您希望找到一个同时包含元素"red" and "blank", without regard to order or other elements in the array, use the $all operator:"red"和"blank"的数组,而不考虑数组中的顺序或其他元素,请使用$all运算符:
MongoDB Shell
db.inventory.find( { tags: { $all: ["red", "blank"] } } )Compass
Copy the following filter into the Compass query bar and click Find:将以下筛选器复制到Compass查询栏中,然后单击“查找”:
{ tags: { $all: ["red", "blank"] } }

C
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);C#
var filter = Builders<BsonDocument>.Filter.All("tags", new[] { "red", "blank" });
var result = collection.Find(filter).ToList();Go
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"tags", bson.D{{"$all", bson.A{"red", "blank"}}}},
})Java(Async)
findPublisher = collection.find(all("tags", asList("red", "blank")));Java(Sync)
findIterable = collection.find(all("tags", asList("red", "blank")));Kotlin(Coroutine)
val findFlow = collection
.find(all("tags", listOf("red", "blank")))Motor
cursor = db.inventory.find({"tags": {"$all": ["red", "blank"]}})Node.js
const cursor = db.collection('inventory').find({
tags: { $all: ['red', 'blank'] }
});PHP
$cursor = $db->inventory->find(['tags' => ['$all' => ['red', 'blank']]]);Python
cursor = db.inventory.find({"tags": {"$all": ["red", "blank"]}})Ruby
client[:inventory].find(tags: { '$all' => ['red', 'blank'] })scala
findObservable = collection.find(all("tags", "red", "blank"))Query an Array for an Element查询数组中的元素
MongoDB Shell
To query if the array field contains at least one element with the specified value, use the filter 要查询数组字段是否包含至少一个具有指定值的元素,请使用筛选器{ <field>: <value> } where <value> is the element value.{ <field>: <value> },其中<value>是元素值。
C
To query if the array field contains at least one element with the specified value, use the filter 要查询数组字段是否包含至少一个具有指定值的元素,请使用筛选器{ <field>: <value> } where <value> is the element value.{ <field>: <value> },其中<value>是元素值。
C#
To query if the array field contains at least one element with the specified value, construct a filter using the Eq method, where 要查询数组字段是否包含至少一个具有指定值的元素,请使用<value> is the element value to match:Eq方法构造一个筛选器,其中<value>是要匹配的元素值:
Builders<BsonDocument>.Filter.Eq(<field>, <value>)Java(Async)
To query if the array field contains at least one element with the specified value, use the filter 要查询数组字段是否包含至少一个具有指定值的元素,请使用筛选器eq( <field>, <value>) where value is the element value.eq( <field>, <value>),其中value是元素值。
Java(Sync)
To query if the array field contains at least one element with the specified value, use the filter 要查询数组字段是否包含至少一个具有指定值的元素,请使用筛选器eq( <field>, <value>) where <value> is the element value.eq( <field>, <value>),其中<value>是元素值。
Motor
To query if the array field contains at least one element with the specified value, use the filter 要查询数组字段是否包含至少一个具有指定值的元素,请使用筛选器{ <field>: <value> } where <value> is the element value.{ <field>: <value> },其中<value>是元素值。
Node.js
To query if the array field contains at least one element with the specified value, use the filter 要查询数组字段是否包含至少一个具有指定值的元素,请使用筛选器{ <field>: <value> } where <value> is the element value.{ <field>: <value> },其中<value>是元素值。
PHP
To query if the array field contains at least one element with the specified value, use the filter 要查询数组字段是否包含至少一个具有指定值的元素,请使用筛选器[ <field> => <value> ] where <value> is the element value.[ <field> => <value> ],其中<value>是元素值。
Python
To query if the array field contains at least one element with the specified value, use the filter 要查询数组字段是否包含至少一个具有指定值的元素,请使用筛选器{ <field>: <value> } where <value> is the element value.{ <field>: <value> },其中<value>是元素值。
Ruby
To query if the array field contains at least one element with the specified value, use the filter 要查询数组字段是否包含至少一个具有指定值的元素,请使用筛选器{ <field> => <value> } where <value> is the element value.{ <field> => <value> },其中<value>是元素值。
scala
To query if the array field contains at least one element with the specified value, use the filter 要查询数组字段是否包含至少一个具有指定值的元素,请使用筛选器equal( <field>, <value> ) where <value> is the element value.equal( <field>, <value> ),其中<value>是元素值。
The following example queries for all documents where 以下示例查询所有tags is an array that contains the string "red" as one of its elements:tags是一个数组的文档,该数组包含字符串"red"作为其元素之一:
MongoDB Shell
db.inventory.find( { tags: "red" } )Compass
Copy the following filter into the Compass query bar and click Find:将以下筛选器复制到Compass查询栏中,然后单击“查找”:
{ tags: "red" }

C
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);C#
var filter = Builders<BsonDocument>.Filter.Eq("tags", "red");
var result = collection.Find(filter).ToList();Go
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"tags", "red"},
})Java(Async)
findPublisher = collection.find(eq("tags", "red"));Java(Sync)
findIterable = collection.find(eq("tags", "red"));Kotlin(Coroutine)
val findFlow = collection
.find(eq("tags", "red"))Motor
cursor = db.inventory.find({"tags": "red"})Node.js
const cursor = db.collection('inventory').find({
tags: 'red'
});PHP
$cursor = $db->inventory->find(['tags' => 'red']);Python
cursor = db.inventory.find({"tags": "red"})Ruby
client[:inventory].find(tags: 'red')scala
findObservable = collection.find(equal("tags", "red"))MongoDB Shell
To specify conditions on the elements in the array field, use query operators in the query filter document:要指定数组字段中元素的条件,请在查询筛选器文档中使用查询运算符:
{ <array field>: { <operator1>: <value1>, ... } }Compass
To specify conditions on the elements in the array field, use query operators in the query filter document:要指定数组字段中元素的条件,请在查询筛选器文档中使用查询运算符:
{ <array field>: { <operator1>: <value1>, ... } }C
To specify conditions on the elements in the array field, use query operators in the query filter document:要指定数组字段中元素的条件,请在查询筛选器文档中使用查询运算符:
{ <array field>: { <operator1>: <value1>, ... } }C#
To specify conditions on the elements in the array field, use query operators in the query filter document. For example:要指定数组字段中元素的条件,请在查询筛选器文档中使用查询运算符。例如:
var builder = Builders<BsonDocument>.Filter;
builder.And(builder.Eq(<array field>, <value1>), builder.Lt(<array field>, <value2>));Java(Async)
To specify conditions on the elements in the array field, use query operators in the query filter document. For example:要指定数组字段中元素的条件,请在查询筛选器文档中使用查询运算符。例如:
and(gte(<array field>, <value1>), lt(<array field>, <value2>) ...)Java(Sync)
To specify conditions on the elements in the array field, use query operators in the query filter document. For example:要指定数组字段中元素的条件,请在查询筛选器文档中使用查询运算符。例如:
and(gte(<array field>, <value1>), lt(<array field>, <value2>) ...)Kotlin(Coroutine)
To specify conditions on the elements in the array field, use query operators in the query filter document. For example:要指定数组字段中元素的条件,请在查询筛选器文档中使用查询运算符。例如:
and(gte(<array field>, <value1>), lt(<array field>, <value2>) ...)Node.js
To specify conditions on the elements in the array field, use query operators in the query filter document:要指定数组字段中元素的条件,请在查询筛选器文档中使用查询运算符:
{ <array field>: { <operator1>: <value1>, ... } }PHP
To specify conditions on the elements in the array field, use query operators in the query filter document:要指定数组字段中元素的条件,请在查询筛选器文档中使用查询运算符:
[ <array field> => [ <operator1> => <value1>, ... ] ]Python
To specify conditions on the elements in the array field, use query operators in the query filter document:要指定数组字段中元素的条件,请在查询筛选器文档中使用查询运算符:
{ <array field>: { <operator1>: <value1>, ... } }Ruby
To specify conditions on the elements in the array field, use query operators in the query filter document:要指定数组字段中元素的条件,请在查询筛选器文档中使用查询运算符:
{ <array field> => { <operator1> => <value1>, ... } }scala
To specify conditions on the elements in the array field, use query operators in the query filter document:要指定数组字段中元素的条件,请在查询筛选器文档中使用查询运算符:
and(gte(<array field>, <value1>), lt(<array field>, <value2>) ...)For example, the following operation queries for all documents where the array 例如,以下操作查询数组dim_cm contains at least one element whose value is greater than 25.dim_cm包含至少一个值大于25的元素的所有文档。
MongoDB Shell
db.inventory.find( { dim_cm: { $gt: 25 } } )Compass
Copy the following filter into the Compass query bar and click Find:将以下筛选器复制到Compass查询栏中,然后单击“查找”:
{ dim_cm: { $gt: 25 } }C
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);C#
var filter = Builders<BsonDocument>.Filter.Gt("dim_cm", 25);
var result = collection.Find(filter).ToList();Go
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"dim_cm", bson.D{
{"$gt", 25},
}},
})Java(Async)
findPublisher = collection.find(gt("dim_cm", 25));Java(Sync)
findIterable = collection.find(gt("dim_cm", 25));Kotlin(Coroutine)
val findFlow = collection
.find(gt("dim_cm", 25))Motor
cursor = db.inventory.find({"dim_cm": {"$gt": 25}})Node.js
const cursor = db.collection('inventory').find({
dim_cm: { $gt: 25 }
});PHP
$cursor = $db->inventory->find(['dim_cm' => ['$gt' => 25]]);Python
cursor = db.inventory.find({"dim_cm": {"$gt": 25}})Ruby
client[:inventory].find(dim_cm: { '$gt' => 25 })scala
findObservable = collection.find(gt("dim_cm", 25))Specify Multiple Conditions for Array Elements为数组元素指定多个条件
When specifying compound conditions on array elements, you can specify the query such that either a single array element meets these condition or any combination of array elements meets the conditions.在数组元素上指定复合条件时,您可以指定查询,使单个数组元素满足这些条件,或者数组元素的任何组合满足这些条件。
Query an Array with Compound Filter Conditions on the Array Elements查询数组元素上具有复合筛选条件的数组
The following example queries for documents where the 以下示例查询dim_cm array contains elements that in some combination satisfy the query conditions; e.g., one element can satisfy the greater than 15 condition and another element can satisfy the less than 20 condition, or a single element can satisfy both:dim_cm数组包含某些组合满足查询条件的元素的文档;例如,一个元素可以满足大于15的条件,另一个元素满足小于20的条件,或者单个元素可以同时满足这两个条件:
MongoDB Shell
db.inventory.find( { dim_cm: { $gt: 15, $lt: 20 } } )Compass
Copy the following filter into the Compass query bar and click Find:将以下筛选器复制到Compass查询栏中,然后单击“查找”:
{ dim_cm: { $gt: 15, $lt: 20 } }

C
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);C#
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();Go
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"dim_cm", bson.D{
{"$gt", 15},
{"$lt", 20},
}},
})Java(Async)
findPublisher = collection.find(and(gt("dim_cm", 15), lt("dim_cm", 20)));Java(Sync)
findIterable = collection.find(and(gt("dim_cm", 15), lt("dim_cm", 20)));Kotlin(Coroutine)
val findFlow = collection
.find(and(gt("dim_cm", 15), lt("dim_cm", 20)))Motor
cursor = db.inventory.find({"dim_cm": {"$gt": 15, "$lt": 20}})Node.js
const cursor = db.collection('inventory').find({
dim_cm: { $gt: 15, $lt: 20 }
});PHP
$cursor = $db->inventory->find([
'dim_cm' => [
'$gt' => 15,
'$lt' => 20,
],
]);Python
cursor = db.inventory.find({"dim_cm": {"$gt": 15, "$lt": 20}})Ruby
client[:inventory].find(dim_cm: { '$gt' => 15,
'$lt' => 20 })scala
findObservable = collection.find(and(gt("dim_cm", 15), lt("dim_cm", 20)))Query for an Array Element that Meets Multiple Criteria查询满足多个条件的数组元素
Use 使用$elemMatch operator to specify multiple criteria on the elements of an array such that at least one array element satisfies all the specified criteria.$elemMatch运算符对数组的元素指定多个条件,以便至少有一个数组元素满足所有指定的条件。
The following example queries for documents where the 以下示例查询dim_cm array contains at least one element that is both greater than ($gt) 22 and less than ($lt) 30:dim_cm数组中至少包含一个大于($gt)22且小于($lt)30的元素的文档:
MongoDB Shell
db.inventory.find( { dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } } )Compass
Copy the following filter into the Compass query bar and click Find:将以下筛选器复制到Compass查询栏中,然后单击“查找”:
{ dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } }

C
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);C#
var filter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>("dim_cm", new BsonDocument { { "$gt", 22 }, { "$lt", 30 } });
var result = collection.Find(filter).ToList();Go
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"dim_cm", bson.D{
{"$elemMatch", bson.D{
{"$gt", 22},
{"$lt", 30},
}},
}},
})Java(Async)
findPublisher = collection.find(elemMatch("dim_cm", Document.parse("{ $gt: 22, $lt: 30 }")));Java(Sync)
findIterable = collection.find(elemMatch("dim_cm", Document.parse("{ $gt: 22, $lt: 30 }")));Kotlin(Coroutine)
val findFlow = collection
.find(elemMatch("dim_cm", Document.parse("{ \$gt: 22, \$lt: 30 }")))Motor
cursor = db.inventory.find({"dim_cm": {"$elemMatch": {"$gt": 22, "$lt": 30}}})Node.js
const cursor = db.collection('inventory').find({
dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } }
});PHP
$cursor = $db->inventory->find([
'dim_cm' => [
'$elemMatch' => [
'$gt' => 22,
'$lt' => 30,
],
],
]);Python
cursor = db.inventory.find({"dim_cm": {"$elemMatch": {"$gt": 22, "$lt": 30}}})Ruby
client[:inventory].find(dim_cm: { '$elemMatch' => { '$gt' => 22,
'$lt' => 30 } })scala
findObservable = collection.find(elemMatch("dim_cm", Document("$gt" -> 22, "$lt" -> 30)))Query for an Element by the Array Index Position按数组索引位置查询元素
Using dot notation, you can specify query conditions for an element at a particular index or position of the array. The array uses zero-based indexing.使用点表示法,您可以在数组的特定索引或位置为元素指定查询条件。数组使用从零开始的索引。
Note
When querying using dot notation, the field and nested field must be inside quotation marks.使用点表示法查询时,字段和嵌套字段必须在引号内。
The following example queries for all documents where the second element in the array 以下示例查询数组dim_cm is greater than 25:dim_cm中第二个元素大于25的所有文档:
MongoDB Shell
db.inventory.find( { "dim_cm.1": { $gt: 25 } } )Compass
Copy the following filter into the Compass query bar and click Find:将以下筛选器复制到Compass查询栏中,然后单击“查找”:
{ "dim_cm.1": { $gt: 25 } }

C
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);C#
var filter = Builders<BsonDocument>.Filter.Gt("dim_cm.1", 25);
var result = collection.Find(filter).ToList();Go
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"dim_cm.1", bson.D{
{"$gt", 25},
}},
})Java(Async)
findPublisher = collection.find(elemMatch("dim_cm", Document.parse("{ $gt: 22, $lt: 30 }")));Java(Sync)
findIterable = collection.find(gt("dim_cm.1", 25));Kotlin(Coroutine)
val findFlow = collection
.find(gt("dim_cm.1", 25))Motor
cursor = db.inventory.find({"dim_cm.1": {"$gt": 25}})Node.js
const cursor = db.collection('inventory').find({
'dim_cm.1': { $gt: 25 }
});PHP
$cursor = $db->inventory->find(['dim_cm.1' => ['$gt' => 25]]);Python
cursor = db.inventory.find({"dim_cm.1": {"$gt": 25}})Ruby
client[:inventory].find('dim_cm.1' => { '$gt' => 25 })scala
findObservable = collection.find(gt("dim_cm.1", 25))Query an Array by Array Length按数组长度查询数组
Use the 使用$size operator to query for arrays by number of elements. For example, the following selects documents where the array tags has 3 elements.$size运算符按元素数量查询数组。例如,下面选择数组tags有3个元素的文档。
MongoDB Shell
db.inventory.find( { "tags": { $size: 3 } } )Compass
Copy the following filter into the Compass query bar and click Find:将以下筛选器复制到Compass查询栏中,然后单击“查找”:
{ "tags": { $size: 3 } }C
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);
Be sure to also clean up any open resources by calling the following methods, as appropriate:请确保根据需要调用以下方法来清理任何开放资源:
C#
var filter = Builders<BsonDocument>.Filter.Size("tags", 3);
var result = collection.Find(filter).ToList();Go
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"tags", bson.D{
{"$size", 3},
}},
})Java(Async)
findPublisher = collection.find(size("tags", 3));Java(Sync)
findIterable = collection.find(size("tags", 3));Kotlin(Coroutine)
val findFlow = collection
.find(size("tags", 3))Motor
cursor = db.inventory.find({"tags": {"$size": 3}})Node.js
const cursor = db.collection('inventory').find({
tags: { $size: 3 }
});PHP
$cursor = $db->inventory->find(['tags' => ['$size' => 3]]);Python
cursor = db.inventory.find({"tags": {"$size": 3}})Ruby
client[:inventory].find(tags: { '$size' => 3 })scala
findObservable = collection.find(size("tags", 3))Query an Array with MongoDB Atlas使用MongoDB Atlas查询数组
The example in this section uses the sample movies dataset. 本节中的示例使用示例电影数据集。To learn how to load the sample dataset into your MongoDB Atlas deployment, see Load Sample Data.要了解如何将示例数据集加载到MongoDB Atlas部署中,请参阅加载示例数据。
To query an array 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_mflixdatabase.sample_mflix数据库。Select the选择moviescollection.movies集合。
Specify a query filter document.指定查询筛选器文档。
To query a document that contains an array, specify a query filter document. A query filter document uses query operators to specify search conditions. 要查询包含数组的文档,请指定查询筛选器文档。查询筛选器文档使用查询运算符指定搜索条件。Use the following example documents to query array fields in the 使用以下示例文档查询sample_mflix.movies collection.sample_mflix.movies集合中的数组字段。
To apply a query filter, copy an example document into the Filter search bar and click Apply.要应用查询筛选器,请将示例文档复制到“筛选器”搜索栏中,然后单击“应用”。
Match an Array匹配数组
To specify an equality condition on an array, use the query document 要在数组上指定相等条件,请使用查询文档{ <field>: <value> } where <value> is the exact array to match, including the order of the elements. { <field>: <value> },其中<value>是要匹配的确切数组,包括元素的顺序。The following example finds documents that have a 以下示例查找具有genres field that contains the ["Action", "Comedy"] array in the specified order:genres(流派)字段的文档,该字段按指定顺序包含["Action", "Comedy"]数组:
{ genres: ["Action", "Comedy"] }
To find an array that contains both the elements 要查找同时包含Action and Comedy, without regard to order or other elements in the array, use the $all operator:Action和Comedy元素的数组,而不考虑数组中的顺序或其他元素,请使用$all运算符:
{ genres: { $all: ["Action", "Comedy"] } }Query for an Element查询元素
To query if the array field contains at least one element with the specified value, use the filter 要查询数组字段是否包含至少一个具有指定值的元素,请使用筛选器{ <field>: <value> } where <value> is the element value.{ <field>: <value> },其中<value>是元素值。
The following example queries for all documents where the 以下示例查询所有genres field contains the string Short as one of its elements:genres字段包含字符串Short作为其元素之一的文档:
{ genres: "Short" }
To specify conditions on the elements in the array field, use query operators in the query filter document:要指定数组字段中元素的条件,请在查询筛选器文档中使用查询运算符:
{ <array field>: { <operator1>: <value1>, ... } }
For example, the following operation uses the 例如,以下操作使用$nin operator to query for all documents where the genres field does not contain Drama.$nin运算符查询genres字段不包含Drama(戏剧)的所有文档。
{ genres: { $nin: ["Drama"] } }Specify Multiple Conditions指定多个条件
When specifying compound conditions on array elements, you can specify the query such that either a single array element meets these condition or any combination of array elements meets the conditions.在数组元素上指定复合条件时,您可以指定查询,使单个数组元素满足这些条件,或者数组元素的任何组合满足这些条件。
Query an Array with Compound Filter Conditions on the Array Elements查询数组元素上具有复合筛选条件的数组
The following example queries for documents where the 以下示例查询其中cast array contains elements that in some combination satisfy the query conditions. cast(演员阵容)数组包含某些组合满足查询条件的元素的文档。For example, the following filter uses the 例如,以下筛选器使用$regex and $eq operators to return documents where a single array element ends in Olsen and another element equals Mary-Kate Olsen or a single element that satisfies both conditions:$regex和$eq运算符返回文档,其中单个数组元素以Olsen结尾,另一个元素等于Mary-Kate Olsen或满足这两个条件的单个元素:
{ cast: { $regex: "Olsen$", $eq: "Mary-Kate Olsen" } }
This query filter returns movies that include 此查询筛选器返回演员阵容中包括Mary-Kate Olsen in their cast, and movies that include both Mary-Kate Olsen and Ashley Olsen in their cast.Mary-Kate Olsen(玛丽·凯特·奥尔森)的电影,以及演员阵容中同时包括Mary-Kate Olsen(玛丽·凯特·奥尔森)和Ashley Olsen(阿什利·奥尔森)的电影。
Query for an Array Element that Meets Multiple Criteria查询满足多个条件的数组元素
Use 使用$elemMatch operator to specify multiple criteria on the elements of an array such that at least one array element satisfies all the specified criteria.$elemMatch运算符对数组的元素指定多个条件,以便至少有一个数组元素满足所有指定的条件。
The following example uses the 以下示例使用$elemMatch and $ne operators to query for documents where the languages array contains at least one element that is both not null and does not equal English.$elemMatch和$ne运算符查询languages数组中至少包含一个非null且不等于English的元素的文档。
{ languages: { $elemMatch: { $ne: null, $ne: "English" } } }Query for an Element by the Array Index Position按数组索引位置查询元素
Using dot notation, you can specify query conditions for an element at a particular index or position of the array. The array uses zero-based indexing.使用点表示法,您可以在数组的特定索引或位置为元素指定查询条件。数组使用从零开始的索引。
Note
When querying using dot notation, the field and nested field must be inside quotation marks.使用点表示法查询时,字段和嵌套字段必须在引号内。
The following example uses the 以下示例使用$ne operator to query for all documents where the first element in the countries array is not equal to USA:$ne运算符查询countries数组中第一个元素不等于USA的所有文档:
{ "countries.0": { $ne: "USA" }Query an Array by Array Length按数组长度查询数组
Use the 使用$size operator to query for arrays by number of elements. For example, the following selects documents where the array genres has 3 elements.$size运算符按元素数量查询数组。例如,下面选择数组genres有3个元素的文档。
{ genres: { $size: 3 } }Additional Query Tutorials其他查询教程
For additional query examples, see:有关其他查询示例,请参阅: