Query an Array查询数组

This page provides examples in:本页提供了以下示例:

This page provides examples of query operations on array fields using the db.collection.find() method in the mongo shell. 本页提供了使用mongo shell中的db.collection.find()方法对数组字段执行查询操作的示例。The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations on array fields using MongoDB Compass. 本页提供了使用MongoDB Compass对数组字段执行查询操作的示例。The examples on this page use the inventory collection. 本页上的示例使用inventory集合。Populate the inventory collection with the following documents:使用以下文档填充inventory集合:

This page provides examples of query operations on array fields using the pymongo.collection.Collection.find() method in the PyMongo Python driver. The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

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. 驱动程序提供com.mongodb.client.model.Filters帮助程序方法,以方便创建筛选文档。The examples on this page use these methods to create the filter documents.本页上的示例使用这些方法创建筛选文档。

The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations on array fields using the Collection.find() method in the MongoDB Node.js Driver. 此页面提供了使用MongoDB Node.js驱动程序中的Collection.find()方法对数组字段执行查询操作的示例。The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations on array fields using the MongoDB\Collection::find() method in the MongoDB PHP Library. The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations on array fields using the motor.motor_asyncio.AsyncIOMotorCollection.find() method in the Motor driver. The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

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反应流驱动程序中的com.mongodb.reactivestreams.client.MongoCollection.find方法对数组字段执行查询操作的示例。

The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations on array fields using the MongoCollection.Find() method in the MongoDB C# Driver. The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations on array fields using the MongoDB::Collection::find() method in the MongoDB Perl Driver. The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations on array fields using the Mongo::Collection#find() method in the MongoDB Ruby Driver. The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations on array fields using the collection.find() method in the MongoDB Scala Driver. The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations on array fields using the Collection.Find function in the MongoDB Go Driver. The examples on this page use the inventory collection. 本页上的示例使用inventory集合。To populate the inventory collection, run the following:要填充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 ] }
]);

You can run the operation in the web shell below:您可以在下面的web shell中运行该操作:

[
  { 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.

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]}])
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 ] }")
));
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]
  }
]);
$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],
    ],
]);
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]}])
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 ] }")
));
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);
$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 ]
        }
    ]
);
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()
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.Background(), docs)

Match an Array匹配数组

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>是要匹配的精确数组,包括元素的顺序。

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>是要匹配的精确数组,包括元素的顺序。

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.

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>是要匹配的精确数组,包括元素的顺序。

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>是要匹配的精确数组,包括元素的顺序。

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.

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.

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>是要匹配的精确数组,包括元素的顺序。

To specify equality condition on an array, construct a filter using the Eq method:

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

<value> is the exact array to match, including the order of the elements.

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.

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.

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.

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"的数组的所有文档:

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

Copy the following filter into the Compass query bar and click Find:将以下筛选器复制到Compass查询栏中,然后单击“查找”:

{ tags: ["red", "blank"] }
../../_images/compass-array-match-exact.png
cursor = db.inventory.find({"tags": ["red", "blank"]})
FindIterable<Document> findIterable = collection.find(eq("tags", asList("red", "blank")));
const cursor = db.collection('inventory').find({
  tags: ['red', 'blank']
});
$cursor = $db->inventory->find(['tags' => ['red', 'blank']]);
cursor = db.inventory.find({"tags": ["red", "blank"]})
FindPublisher<Document> findPublisher = collection.find(eq("tags", asList("red", "blank")));
var filter = Builders<BsonDocument>.Filter.Eq("tags", new[] { "red", "blank" });
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find( { tags => [ "red", "blank" ] } );
client[:inventory].find(tags: ['red', 'blank'])
var findObservable = collection.find(equal("tags", Seq("red", "blank")))
cursor, err := coll.Find(
	context.Background(),
	bson.D{{"tags", bson.A{"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运算符:

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

Copy the following filter into the Compass query bar and click Find:将以下筛选器复制到Compass查询栏中,然后单击“查找”:

{ tags: { $all: ["red", "blank"] } }
../../_images/compass-array-match-all.png
cursor = db.inventory.find({"tags": {"$all": ["red", "blank"]}})
findIterable = collection.find(all("tags", asList("red", "blank")));
const cursor = db.collection('inventory').find({
  tags: { $all: ['red', 'blank'] }
});
$cursor = $db->inventory->find(['tags' => ['$all' => ['red', 'blank']]]);
cursor = db.inventory.find({"tags": {"$all": ["red", "blank"]}})
findPublisher = collection.find(all("tags", asList("red", "blank")));
var filter = Builders<BsonDocument>.Filter.All("tags", new[] { "red", "blank" });
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find( { tags => { '$all' => [ "red", "blank" ] } } );
client[:inventory].find(tags: { '$all' => ['red', 'blank'] })
findObservable = collection.find(all("tags", "red", "blank"))
cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"tags", bson.D{{"$all", bson.A{"red", "blank"}}}},
	})

Query an Array 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>是元素值。

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.

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>是元素值。

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>是元素值。

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.

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.

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是元素值。

To query if the array field contains at least one element with the specified value, construct a filter using the Eq method:

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

<value> is the element value to match.

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.

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.

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.

The following example queries for all documents where tags is an array that contains the string "red" as one of its elements:以下示例查询所有文档,其中tags是包含字符串"red"作为其元素之一的数组:

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

Copy the following filter into the Compass query bar and click Find:将以下筛选器复制到Compass查询栏中,然后单击“查找”:

{ tags: "red" }
../../_images/compass-array-elem-match.png
cursor = db.inventory.find({"tags": "red"})
findIterable = collection.find(eq("tags", "red"));
const cursor = db.collection('inventory').find({
  tags: 'red'
});
$cursor = $db->inventory->find(['tags' => 'red']);
cursor = db.inventory.find({"tags": "red"})
findPublisher = collection.find(eq("tags", "red"));
var filter = Builders<BsonDocument>.Filter.Eq("tags", "red");
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find( { tags => "red" } );
client[:inventory].find(tags: 'red')
findObservable = collection.find(equal("tags", "red"))
cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"tags", "red"},
	})

To specify conditions on the elements in the array field, use query operators in the query filter document:要指定数组字段中元素的条件,请在查询筛选器文档中使用查询运算符

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

To specify conditions on the elements in the array field, use query operators in the query filter document:要指定数组字段中元素的条件,请在查询筛选器文档中使用查询运算符

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

To specify conditions on the elements in the array field, use query operators in the query filter document:

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

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>) ...)

To specify conditions on the elements in the array field, use query operators in the query filter document:要指定数组字段中元素的条件,请在查询筛选器文档中使用查询运算符

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

To specify conditions on the elements in the array field, use query operators in the query filter document:

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

To specify conditions on the elements in the array field, use query operators in the query filter document:

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

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>) ...)

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>));

To specify conditions on the elements in the array field, use query operators in the query filter document:

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

To specify conditions on the elements in the array field, use query operators in the query filter document:

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

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的元素的所有文档。

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

Copy the following filter into the Compass query bar and click Find:将以下筛选器复制到Compass查询栏中,然后单击“查找”:

{ dim_cm: { $gt: 25 } }
../../_images/compass-array-query-op.png
cursor = db.inventory.find({"dim_cm": {"$gt": 25}})
findIterable = collection.find(gt("dim_cm", 25));
const cursor = db.collection('inventory').find({
  dim_cm: { $gt: 25 }
});
$cursor = $db->inventory->find(['dim_cm' => ['$gt' => 25]]);
cursor = db.inventory.find({"dim_cm": {"$gt": 25}})
findPublisher = collection.find(gt("dim_cm", 25));
var filter = Builders<BsonDocument>.Filter.Gt("dim_cm", 25);
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find( { "dim_cm" => { '$gt' => 25 } } );
client[:inventory].find(dim_cm: { '$gt' => 25 })
findObservable = collection.find(gt("dim_cm", 25))
cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"dim_cm", bson.D{
			{"$gt", 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的条件,或者一个元素可以同时满足这两个条件:

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

Copy the following filter into the Compass query bar and click Find:将以下筛选器复制到Compass查询栏中,然后单击“查找”:

{ dim_cm: { $gt: 15, $lt: 20 } }
../../_images/compass-array-compound-filter.png
cursor = db.inventory.find({"dim_cm": {"$gt": 15, "$lt": 20}})
findIterable = collection.find(and(gt("dim_cm", 15), lt("dim_cm", 20)));
const cursor = db.collection('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}})
findPublisher = collection.find(and(gt("dim_cm", 15), lt("dim_cm", 20)));
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 = $db->coll("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)))
cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"dim_cm", bson.D{
			{"$gt", 15},
			{"$lt", 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数组中至少包含一个大于($gt22且小于($lt30的元素的文档:

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

Copy the following filter into the Compass query bar and click Find:将以下筛选器复制到Compass查询栏中,然后单击“查找”:

{ dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } }
../../_images/compass-array-compound-multiple-criteria.png
cursor = db.inventory.find(
    {"dim_cm": {"$elemMatch": {"$gt": 22, "$lt": 30}}})
findIterable = collection.find(elemMatch("dim_cm", Document.parse("{ $gt: 22, $lt: 30 }")));
const cursor = db.collection('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}}})
findPublisher = collection.find(elemMatch("dim_cm", Document.parse("{ $gt: 22, $lt: 30 }")));
var filter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>("dim_cm", new BsonDocument { { "$gt", 22 }, { "$lt", 30 } });
var result = collection.Find(filter).ToList();
$cursor = $db->coll("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)))
cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"dim_cm", bson.D{
			{"$elemMatch", bson.D{
				{"$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的所有文档:

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

Copy the following filter into the Compass query bar and click Find:将以下筛选器复制到Compass查询栏中,然后单击“查找”:

{ "dim_cm.1": { $gt: 25 } }
../../_images/compass-array-match-by-index.png
cursor = db.inventory.find({"dim_cm.1": {"$gt": 25}})
findIterable = collection.find(gt("dim_cm.1", 25));
const cursor = db.collection('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}})
findPublisher = collection.find(elemMatch("dim_cm", Document.parse("{ $gt: 22, $lt: 30 }")));
var filter = Builders<BsonDocument>.Filter.Gt("dim_cm.1", 25);
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find( { "dim_cm.1" => { '$gt' => 25 } } );
client[:inventory].find('dim_cm.1' => { '$gt' => 25 })
findObservable = collection.find(gt("dim_cm.1", 25))
cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"dim_cm.1", bson.D{
			{"$gt", 25},
		}},
	})

Query an Array by Array Length按数组长度查询数组

Use the $size operator to query for arrays by number of elements. 使用$size运算符按元素数查询数组。For example, the following selects documents where the array tags has 3 elements.例如,下面选择数组tags有3个元素的文档。

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

Copy the following filter into the Compass query bar and click Find:将以下筛选器复制到Compass查询栏中,然后单击“查找”:

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

Additional Query Tutorials附加查询教程

For additional query examples, see:有关其他查询示例,请参阅: