Query an Array of Embedded Documents查询嵌入文档的数组

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

This page provides examples of query operations on an array of nested documents 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 an array of nested documents 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 an array of nested documents 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 an array of nested documents 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. 本页上的示例使用库存集合。To populate the inventory collection, run the following:要填充inventory集合,请运行以下操作:

This page provides examples of query operations on an array of nested documents 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 an array of nested documents 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 an array of nested documents 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 an array of nested documents 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 an array of nested documents 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 an array of nested documents 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 an array of nested documents 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 an array of nested documents 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 an array of nested documents 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", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
   { item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
   { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
   { item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
   { item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);

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

[
   { item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
   { item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
   { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
   { item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
   { item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]

For instructions on inserting documents in MongoDB Compass, see Insert Documents.有关在MongoDB Compass中插入文档的说明,请参阅插入文档

# Subdocument key order matters in a few of these examples so we have
# to use bson.son.SON instead of a Python dict.
from bson.son import SON
db.inventory.insert_many([
    {"item": "journal",
     "instock": [
         SON([("warehouse", "A"), ("qty", 5)]),
         SON([("warehouse", "C"), ("qty", 15)])]},
    {"item": "notebook",
     "instock": [
         SON([("warehouse", "C"), ("qty", 5)])]},
    {"item": "paper",
     "instock": [
         SON([("warehouse", "A"), ("qty", 60)]),
         SON([("warehouse", "B"), ("qty", 15)])]},
    {"item": "planner",
     "instock": [
         SON([("warehouse", "A"), ("qty", 40)]),
         SON([("warehouse", "B"), ("qty", 5)])]},
    {"item": "postcard",
     "instock": [
         SON([("warehouse", "B"), ("qty", 15)]),
         SON([("warehouse", "C"), ("qty", 35)])]}])
collection.insertMany(asList(
        Document.parse("{ item: 'journal', instock: [ { warehouse: 'A', qty: 5 }, { warehouse: 'C', qty: 15 } ] }"),
        Document.parse("{ item: 'notebook', instock: [ { warehouse: 'C', qty: 5 } ] }"),
        Document.parse("{ item: 'paper', instock: [ { warehouse: 'A', qty: 60 }, { warehouse: 'B', qty: 15 } ] }"),
        Document.parse("{ item: 'planner', instock: [ { warehouse: 'A', qty: 40 }, { warehouse: 'B', qty: 5 } ] }"),
        Document.parse("{ item: 'postcard', instock: [ { warehouse: 'B', qty: 15 }, { warehouse: 'C', qty: 35 } ] }")
));
await db.collection('inventory').insertMany([
  {
    item: 'journal',
    instock: [
      { warehouse: 'A', qty: 5 },
      { warehouse: 'C', qty: 15 }
    ]
  },
  {
    item: 'notebook',
    instock: [{ warehouse: 'C', qty: 5 }]
  },
  {
    item: 'paper',
    instock: [
      { warehouse: 'A', qty: 60 },
      { warehouse: 'B', qty: 15 }
    ]
  },
  {
    item: 'planner',
    instock: [
      { warehouse: 'A', qty: 40 },
      { warehouse: 'B', qty: 5 }
    ]
  },
  {
    item: 'postcard',
    instock: [
      { warehouse: 'B', qty: 15 },
      { warehouse: 'C', qty: 35 }
    ]
  }
]);
$insertManyResult = $db->inventory->insertMany([
    [
        'item' => 'journal',
        'instock' => [
            ['warehouse' => 'A',  'qty' => 5],
            ['warehouse' => 'C',  'qty' => 15],
        ],
    ],
    [
        'item' => 'notebook',
        'instock' => [
            ['warehouse' => 'C',  'qty' => 5],
        ],
    ],
    [
        'item' => 'paper',
        'instock' => [
            ['warehouse' => 'A',  'qty' => 60],
            ['warehouse' => 'B',  'qty' => 15],
        ],
    ],
    [
        'item' => 'planner',
        'instock' => [
            ['warehouse' => 'A',  'qty' => 40],
            ['warehouse' => 'B',  'qty' => 5],
        ],
    ],
    [
        'item' => 'postcard',
        'instock' => [
            ['warehouse' => 'B',  'qty' => 15],
            ['warehouse' => 'C',  'qty' => 35],
        ],
    ],
]);
# Subdocument key order matters in a few of these examples so we have
# to use bson.son.SON instead of a Python dict.
from bson.son import SON
await db.inventory.insert_many([
    {"item": "journal",
     "instock": [
         SON([("warehouse", "A"), ("qty", 5)]),
         SON([("warehouse", "C"), ("qty", 15)])]},
    {"item": "notebook",
     "instock": [
         SON([("warehouse", "C"), ("qty", 5)])]},
    {"item": "paper",
     "instock": [
         SON([("warehouse", "A"), ("qty", 60)]),
         SON([("warehouse", "B"), ("qty", 15)])]},
    {"item": "planner",
     "instock": [
         SON([("warehouse", "A"), ("qty", 40)]),
         SON([("warehouse", "B"), ("qty", 5)])]},
    {"item": "postcard",
     "instock": [
         SON([("warehouse", "B"), ("qty", 15)]),
         SON([("warehouse", "C"), ("qty", 35)])]}])
Publisher<Success> insertManyPublisher = collection.insertMany(asList(
        Document.parse("{ item: 'journal', instock: [ { warehouse: 'A', qty: 5 }, { warehouse: 'C', qty: 15 } ] }"),
        Document.parse("{ item: 'notebook', instock: [ { warehouse: 'C', qty: 5 } ] }"),
        Document.parse("{ item: 'paper', instock: [ { warehouse: 'A', qty: 60 }, { warehouse: 'B', qty: 15 } ] }"),
        Document.parse("{ item: 'planner', instock: [ { warehouse: 'A', qty: 40 }, { warehouse: 'B', qty: 5 } ] }"),
        Document.parse("{ item: 'postcard', instock: [ { warehouse: 'B', qty: 15 }, { warehouse: 'C', qty: 35 } ] }")
));
var documents = new[]
{
    new BsonDocument
    {
        { "item", "journal" },
        { "instock", new BsonArray
            {
                new BsonDocument { { "warehouse", "A" }, { "qty", 5 } },
                new BsonDocument { { "warehouse", "C" }, { "qty", 15 } } }
            }
    },
    new BsonDocument
    {
        { "item", "notebook" },
        { "instock", new BsonArray
            {
                new BsonDocument { { "warehouse", "C" }, { "qty", 5 } } }
            }
    },
    new BsonDocument
    {
        { "item", "paper" },
        { "instock", new BsonArray
            {
                new BsonDocument { { "warehouse", "A" }, { "qty", 60 } },
                new BsonDocument { { "warehouse", "B" }, { "qty", 15 } } }
            }
    },
    new BsonDocument
    {
        { "item", "planner" },
        { "instock", new BsonArray
            {
                new BsonDocument { { "warehouse", "A" }, { "qty", 40 } },
                new BsonDocument { { "warehouse", "B" }, { "qty", 5 } } }
            }
    },
    new BsonDocument
    {
        { "item", "postcard" },
        { "instock", new BsonArray
            {
                new BsonDocument { { "warehouse", "B" }, { "qty", 15 } },
                new BsonDocument { { "warehouse", "C" }, { "qty", 35 } } }
            }
    }
};
collection.InsertMany(documents);
# Subdocument key order matters in this example so we have
# to use Tie::IxHash instead of a regular, unordered Perl hash.
$db->coll("inventory")->insert_many(
    [
        {
            item    => "journal",
            instock => [
                Tie::IxHash->new( warehouse => "A", qty => 5 ),
                Tie::IxHash->new( warehouse => "C", qty => 15 )
            ]
        },
        {
            item    => "notebook",
            instock => [ Tie::IxHash->new( warehouse => "C", qty => 5 ) ]
        },
        {
            item    => "paper",
            instock => [
                Tie::IxHash->new( warehouse => "A", qty => 60 ),
                Tie::IxHash->new( warehouse => "B", qty => 15 )
            ]
        },
        {
            item    => "planner",
            instock => [
                Tie::IxHash->new( warehouse => "A", qty => 40 ),
                Tie::IxHash->new( warehouse => "B", qty => 5 )
            ]
        },
        {
            item    => "postcard",
            instock => [
                Tie::IxHash->new( warehouse => "B", qty => 15 ),
                Tie::IxHash->new( warehouse => "C", qty => 35 )
            ]
        }
    ]
);
client[:inventory].insert_many([{ item: 'journal',
                                  instock: [ { warehouse: 'A', qty: 5 },
                                             { warehouse: 'C', qty: 15 }] },
                                { item: 'notebook',
                                  instock: [ { warehouse: 'C', qty: 5 }] },
                                { item: 'paper',
                                  instock: [ { warehouse: 'A', qty: 60 },
                                             { warehouse: 'B', qty: 15 }] },
                                { item: 'planner',
                                  instock: [ { warehouse: 'A', qty: 40 },
                                             { warehouse: 'B', qty: 5 }] },
                                { item: 'postcard',
                                  instock: [ { warehouse: 'B', qty: 15 },
                                             { warehouse: 'C', qty: 35 }] }
                               ])
collection.insertMany(Seq(
  Document("""{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] }"""),
  Document("""{ item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] }"""),
  Document("""{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] }"""),
  Document("""{ item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] }"""),
  Document("""{ item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }""")
)).execute()
docs := []interface{}{
	bson.D{
		{"item", "journal"},
		{"instock", bson.A{
			bson.D{
				{"warehouse", "A"},
				{"qty", 5},
			},
			bson.D{
				{"warehouse", "C"},
				{"qty", 15},
			},
		}},
	},
	bson.D{
		{"item", "notebook"},
		{"instock", bson.A{
			bson.D{
				{"warehouse", "C"},
				{"qty", 5},
			},
		}},
	},
	bson.D{
		{"item", "paper"},
		{"instock", bson.A{
			bson.D{
				{"warehouse", "A"},
				{"qty", 60},
			},
			bson.D{
				{"warehouse", "B"},
				{"qty", 15},
			},
		}},
	},
	bson.D{
		{"item", "planner"},
		{"instock", bson.A{
			bson.D{
				{"warehouse", "A"},
				{"qty", 40},
			},
			bson.D{
				{"warehouse", "B"},
				{"qty", 5},
			},
		}},
	},
	bson.D{
		{"item", "postcard"},
		{"instock", bson.A{
			bson.D{
				{"warehouse", "B"},
				{"qty", 15},
			},
			bson.D{
				{"warehouse", "C"},
				{"qty", 35},
			},
		}},
	},
}

result, err := coll.InsertMany(context.Background(), docs)

Query for a Document Nested in an Array查询嵌套在数组中的文档

The following example selects all documents where an element in the instock array matches the specified document:以下示例选择instock数组中的元素与指定文档匹配的所有文档:

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

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

{ "instock": { warehouse: "A", qty: 5 } }
../../_images/compass-find-nested-in-array.png
cursor = db.inventory.find(
    {"instock": SON([("warehouse", "A"), ("qty", 5)])})
FindIterable<Document> findIterable = collection.find(eq("instock", Document.parse("{ warehouse: 'A', qty: 5 }")));
const cursor = db.collection('inventory').find({
  instock: { warehouse: 'A', qty: 5 }
});
$cursor = $db->inventory->find(['instock' => ['warehouse' => 'A', 'qty' => 5]]);
cursor = db.inventory.find(
    {"instock": SON([("warehouse", "A"), ("qty", 5)])})
FindPublisher<Document> findPublisher = collection.find(eq("instock", Document.parse("{ warehouse: 'A', qty: 5 }")));
var filter = Builders<BsonDocument>.Filter.AnyEq("instock", new BsonDocument { { "warehouse", "A" }, { "qty", 5 } });
var result = collection.Find(filter).ToList();
# Subdocument key order matters in this example so we have
# to use Tie::IxHash instead of a regular, unordered Perl hash.
$cursor = $db->coll("inventory")->find(
    { instock => Tie::IxHash->new( warehouse => "A", qty => 5 ) }
);
client[:inventory].find(instock: { warehouse: 'A', qty: 5 })
var findObservable = collection.find(equal("instock", Document("warehouse" -> "A", "qty" -> 5)))
cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"instock", bson.D{
			{"warehouse", "A"},
			{"qty", 5},
		}},
	})

Equality matches on the whole embedded/nested document require an exact match of the specified document, including the field order. 整个嵌入/嵌套文档的相等匹配要求与指定文档(包括字段顺序)精确匹配。For example, the following query does not match any documents in the inventory collection:例如,以下查询与inventory集合中的任何文档都不匹配:

db.inventory.find( { "instock": { qty: 5, warehouse: "A" } } )
../../_images/compass-find-nested-array-no-match.png
cursor = db.inventory.find(
    {"instock": SON([("qty", 5), ("warehouse", "A")])})
findIterable = collection.find(eq("instock", Document.parse("{ qty: 5, warehouse: 'A' }")));
const cursor = db.collection('inventory').find({
  instock: { qty: 5, warehouse: 'A' }
});
$cursor = $db->inventory->find(['instock' => ['qty' => 5, 'warehouse' => 'A']]);
cursor = db.inventory.find(
    {"instock": SON([("qty", 5), ("warehouse", "A")])})
findPublisher = collection.find(eq("instock", Document.parse("{ qty: 5, warehouse: 'A' }")));
var filter = Builders<BsonDocument>.Filter.AnyEq("instock", new BsonDocument { { "qty", 5 }, { "warehouse", "A" } });
var result = collection.Find(filter).ToList();
# Subdocument key order matters in this example so we have
# to use Tie::IxHash instead of a regular, unordered Perl hash.
$cursor = $db->coll("inventory")->find(
    { instock => Tie::IxHash->new( qty => 5, warehouse => "A" ) }
);
client[:inventory].find(instock: { qty: 5, warehouse: 'A' } )
findObservable = collection.find(equal("instock", Document("qty" -> 5, "warehouse" -> "A")))
cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"instock", bson.D{
			{"qty", 5},
			{"warehouse", "A"},
		}},
	})

Specify a Query Condition on a Field in an Array of Documents在文档数组中的字段上指定查询条件

Specify a Query Condition on a Field Embedded in an Array of Documents对嵌入在文档数组中的字段指定查询条件

If you do not know the index position of the document nested in the array, concatenate the name of the array field, with a dot (.) and the name of the field in the nested document.如果不知道嵌套在数组中的文档的索引位置,请将数组字段的名称与点(.)和嵌套文档中的字段名称连接起来。

The following example selects all documents where the instock array has at least one embedded document that contains the field qty whose value is less than or equal to 20:以下示例选择instock数组中至少有一个嵌入文档的所有文档,其中包含字段qty其值小于或等于20

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

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

{ 'instock.qty': { $lte: 20 } }
../../_images/compass-find-array-embedded-field-condition.png
cursor = db.inventory.find({'instock.qty': {"$lte": 20}})
findIterable = collection.find(lte("instock.qty", 20));
const cursor = db.collection('inventory').find({
  'instock.qty': { $lte: 20 }
});
$cursor = $db->inventory->find(['instock.qty' => ['$lte' => 20]]);
cursor = db.inventory.find({'instock.qty': {"$lte": 20}})
findPublisher = collection.find(lte("instock.qty", 20));
var filter = Builders<BsonDocument>.Filter.Lte("instock.qty", 20);
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find( { 'instock.qty' => { '$lte' => 20 } } );
client[:inventory].find('instock.qty' => { '$lte' => 20 })
findObservable = collection.find(lte("instock.qty", 20))
cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"instock.qty", bson.D{
			{"$lte", 20},
		}},
	})

Use the Array Index to Query for a Field in the Embedded Document使用数组索引查询嵌入文档中的字段

Using dot notation, you can specify query conditions for field in a document at a particular index or position of the array. 使用点表示法,可以为文档中特定索引或数组位置的字段指定查询条件。The array uses zero-based indexing.该数组使用基于零的索引。

Note

When querying using dot notation, the field and index must be inside quotation marks.使用点表示法进行查询时,字段和索引必须位于引号内。

The following example selects all documents where the instock array has as its first element a document that contains the field qty whose value is less than or equal to 20:以下示例选择instock数组的第一个元素为包含字段qty(其值小于或等于20)的文档的所有文档:

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

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

{ 'instock.0.qty': { $lte: 20 } }
../../_images/compass-find-array-index-embedded-doc.png
cursor = db.inventory.find({'instock.0.qty': {"$lte": 20}})
findIterable = collection.find(lte("instock.0.qty", 20));
const cursor = db.collection('inventory').find({
  'instock.0.qty': { $lte: 20 }
});
$cursor = $db->inventory->find(['instock.0.qty' => ['$lte' => 20]]);
cursor = db.inventory.find({'instock.0.qty': {"$lte": 20}})
findPublisher = collection.find(lte("instock.0.qty", 20));
var filter = Builders<BsonDocument>.Filter.Lte("instock.0.qty", 20);
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find( { 'instock.0.qty' => { '$lte' => 20 } } );
client[:inventory].find('instock.0.qty' => { '$lte' => 20 })
findObservable = collection.find(lte("instock.0.qty", 20))
cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"instock.0.qty", bson.D{
			{"$lte", 20},
		}},
	})

Specify Multiple Conditions for Array of Documents为文档数组指定多个条件

When specifying conditions on more than one field nested in an array of documents, you can specify the query such that either a single document meets these condition or any combination of documents (including a single document) in the array meets the conditions.在对嵌套在文档数组中的多个字段指定条件时,可以指定查询,以便单个文档满足这些条件,或者数组中的任何文档组合(包括单个文档)满足这些条件。

A Single Nested Document Meets Multiple Query Conditions on Nested Fields单个嵌套文档满足嵌套字段的多个查询条件

Use $elemMatch operator to specify multiple criteria on an array of embedded documents such that at least one embedded document satisfies all the specified criteria.使用$elemMatch运算符在嵌入文档数组上指定多个条件,以便至少一个嵌入文档满足所有指定条件。

The following example queries for documents where the instock array has at least one embedded document that contains both the field qty equal to 5 and the field warehouse equal to A:以下示例查询instock数组中至少有一个包含字段qty等于5和字段warehouse等于A的嵌入文档的文档:

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

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

{ "instock": { $elemMatch: { qty: 5, warehouse: "A" } } }
../../_images/compass-array-multiple-cond-single-doc.png
cursor = db.inventory.find(
    {"instock": {"$elemMatch": {"qty": 5, "warehouse": "A"}}})
findIterable = collection.find(elemMatch("instock", Document.parse("{ qty: 5, warehouse: 'A' }")));
const cursor = db.collection('inventory').find({
  instock: { $elemMatch: { qty: 5, warehouse: 'A' } }
});
$cursor = $db->inventory->find(['instock' => ['$elemMatch' => ['qty' => 5, 'warehouse' => 'A']]]);
cursor = db.inventory.find(
    {"instock": {"$elemMatch": {"qty": 5, "warehouse": "A"}}})
findPublisher = collection.find(elemMatch("instock", Document.parse("{ qty: 5, warehouse: 'A' }")));
var filter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>("instock", new BsonDocument { { "qty", 5 }, { "warehouse", "A" } });
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find(
    { instock => { '$elemMatch' => { qty => 5, warehouse => "A" } } }
);
client[:inventory].find(instock: { '$elemMatch' => { qty: 5,
                                                     warehouse: 'A' } })
findObservable = collection.find(elemMatch("instock", Document("qty" -> 5, "warehouse" -> "A")))
cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"instock", bson.D{
			{"$elemMatch", bson.D{
				{"qty", 5},
				{"warehouse", "A"},
			}},
		}},
	})

The following example queries for documents where the instock array has at least one embedded document that contains the field qty that is greater than 10 and less than or equal to 20:以下示例查询instock数组中至少有一个嵌入文档包含字段qty其值大于10且小于或等于20的文档:

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

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

{ "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } }
../../_images/compass-array-multiple-cond-single-doc-2.png
cursor = db.inventory.find(
    {"instock": {"$elemMatch": {"qty": {"$gt": 10, "$lte": 20}}}})
findIterable = collection.find(elemMatch("instock", Document.parse("{ qty: { $gt: 10, $lte: 20 } }")));
const cursor = db.collection('inventory').find({
  instock: { $elemMatch: { qty: { $gt: 10, $lte: 20 } } }
});
$cursor = $db->inventory->find(['instock' => ['$elemMatch' => ['qty' => ['$gt' => 10, '$lte' => 20]]]]);
cursor = db.inventory.find(
    {"instock": {"$elemMatch": {"qty": {"$gt": 10, "$lte": 20}}}})
findPublisher = collection.find(elemMatch("instock", Document.parse("{ qty: { $gt: 10, $lte: 20 } }")));
var filter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>("instock", new BsonDocument { { "qty", new BsonDocument { { "$gt", 10 }, { "$lte", 20 } } } });
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory") ->find(
    { instock => { '$elemMatch' => { qty => { '$gt' => 10, '$lte' => 20 } } } }
);
client[:inventory].find(instock: { '$elemMatch' => { qty: { '$gt'  => 10,
                                                            '$lte' => 20 } } })
findObservable = collection.find(elemMatch("instock", Document("""{ qty: { $gt: 10, $lte: 20 } }""")))
cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"instock", bson.D{
			{"$elemMatch", bson.D{
				{"qty", bson.D{
					{"$gt", 10},
					{"$lte", 20},
				}},
			}},
		}},
	})

Combination of Elements Satisfies the Criteria元素的组合满足标准

If the compound query conditions on an array field do not use the $elemMatch operator, the query selects those documents whose array contains any combination of elements that satisfies the conditions.如果数组字段上的复合查询条件不使用$elemMatch运算符,则查询将选择其数组包含满足条件的任何元素组合的文档。

For example, the following query matches documents where any document nested in the instock array has the qty field greater than 10 and any document (but not necessarily the same embedded document) in the array has the qty field less than or equal to 20:例如,以下查询匹配instock数组中嵌套的任何文档的qty字段大于10且数组中嵌套的任何文档(但不一定是同一嵌入文档)的qty字段小于或等于20的文档:

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

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

{ "instock.qty": { $gt: 10,  $lte: 20 } }
../../_images/compass-array-match-combination-of-elements.png
cursor = db.inventory.find({"instock.qty": {"$gt": 10, "$lte": 20}})
findIterable = collection.find(and(gt("instock.qty", 10), lte("instock.qty", 20)));
const cursor = db.collection('inventory').find({
  'instock.qty': { $gt: 10, $lte: 20 }
});
$cursor = $db->inventory->find(['instock.qty' => ['$gt' => 10, '$lte' => 20]]);
cursor = db.inventory.find({"instock.qty": {"$gt": 10, "$lte": 20}})
findPublisher = collection.find(and(gt("instock.qty", 10), lte("instock.qty", 20)));
var builder = Builders<BsonDocument>.Filter;
var filter = builder.And(builder.Gt("instock.qty", 10), builder.Lte("instock.qty", 20));
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find(
    { "instock.qty" => { '$gt' => 10, '$lte' => 20 } }
);
client[:inventory].find('instock.qty' => { '$gt' => 10, '$lte' => 20 })
findObservable = collection.find(and(gt("instock.qty", 10), lte("instock.qty", 20)))
cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"instock.qty", bson.D{
			{"$gt", 10},
			{"$lte", 20},
		}},
	})

The following example queries for documents where the instock array has at least one embedded document that contains the field qty equal to 5 and at least one embedded document (but not necessarily the same embedded document) that contains the field warehouse equal to A:以下示例查询instock数组中至少有一个包含字段qty等于5的嵌入文档和至少一个包含字段warehouse等于A的嵌入文档(但不一定是同一个嵌入文档)的文档:

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

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

{ "instock.qty": 5, "instock.warehouse": "A" }
../../_images/compass-array-match-combination-of-elements-2.png
cursor = db.inventory.find(
    {"instock.qty": 5, "instock.warehouse": "A"})
findIterable = collection.find(and(eq("instock.qty", 5), eq("instock.warehouse", "A")));
const cursor = db.collection('inventory').find({
  'instock.qty': 5,
  'instock.warehouse': 'A'
});
$cursor = $db->inventory->find(['instock.qty' => 5, 'instock.warehouse' => 'A']);
cursor = db.inventory.find(
    {"instock.qty": 5, "instock.warehouse": "A"})
findPublisher = collection.find(and(eq("instock.qty", 5), eq("instock.warehouse", "A")));
var builder = Builders<BsonDocument>.Filter;
var filter = builder.And(builder.Eq("instock.qty", 5), builder.Eq("instock.warehouse", "A"));
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find(
    { "instock.qty" => 5, "instock.warehouse" => "A" }
);
client[:inventory].find('instock.qty' => 5,
                        'instock.warehouse' => 'A')
findObservable = collection.find(and(equal("instock.qty", 5), equal("instock.warehouse", "A")))
cursor, err := coll.Find(
	context.Background(),
	bson.D{
		{"instock.qty", 5},
		{"instock.warehouse", "A"},
	})

Additional Query Tutorials附加查询教程

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