查询嵌入式文档数组

Mongo Shell
Compass
Python
Java (Sync)
Node.js
PHP
Motor
Java (Async)
C#
Perl
Ruby
Scala

This page provides examples of query operations on an array of nested documents using the db.collection.find() method in the mongo shell. The examples on this page use the inventory collection. To populate the inventory collection, run the following:

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:

MongoDB Web Shell

This page provides examples of query operations on an array of nested documents using MongoDB Compass. The examples on this page use the inventory collection. Populate the inventory collection with the following documents:

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

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. To populate the inventory collection, run the following:

# 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)])]}])

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.

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.

The examples on this page use the inventory collection. To populate the inventory collection, run the following:

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 } ] }")
));

This page provides examples of query operations on an array of nested documents using the Collection.find() method in the MongoDB Node.js Driver. The examples on this page use the inventory collection. To populate the inventory collection, run the following:

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

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. To populate the inventory collection, run the following:

$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],
        ],
    ],
]);

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. To populate the inventory collection, run the following:

# 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)])]}])

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.

The examples on this page use the inventory collection. To populate the inventory collection, run the following:

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 } ] }")
));

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. To populate the inventory collection, run the following:

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

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. To populate the inventory collection, run the following:

# 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 )
            ]
        }
    ]
);

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. To populate the inventory collection, run the following:

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 }] }
                               ])

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. To populate the inventory collection, run the following:

collection.insertMany(Seq(
  Document("""{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] }"""),
  Document("""{ item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] }"""),
  Document("""{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] }"""),
  Document("""{ item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] }"""),
  Document("""{ item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }""")
)).execute()

查询嵌套在数组中的文档

下面的示例选择instock数组中的元素与指定文档匹配的所有文档:

Mongo Shell
Compass
Python
Java (Sync)
Node.js
PHP
Motor
Java (Async)
C#
Perl
Ruby
Scala
db.inventory.find( { "instock": { warehouse: "A", qty: 5 } } )

Copy the following filter into the Compass query bar and click Find:

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

整个嵌入式/嵌套文档上的相等匹配要求指定文档的“精确”匹配,包括字段 Sequences。例如,以下查询与inventory集合中的任何文档都不匹配:

Mongo Shell
Compass
Python
Java (Sync)
Node.js
PHP
Motor
Java (Async)
C#
Perl
Ruby
Scala
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")))

在文档数组中的字段上指定查询条件

在嵌入文档数组中的字段上指定查询条件

如果您不知道嵌套在数组中的文档的索引位置,请使用点(.)和嵌套文档中的字段名称将数组字段的名称连接起来。

下面的示例选择所有instock1 数组具有至少一个嵌入式文档的嵌入式文档,这些文档包含字段qty的值小于或等于20

Mongo Shell
Compass
Python
Java (Sync)
Node.js
PHP
Motor
Java (Async)
C#
Perl
Ruby
Scala
db.inventory.find( { 'instock.qty': { $lte: 20 } } )

Copy the following filter into the Compass query bar and click Find:

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

使用数组索引查询嵌入式文档中的字段

使用dot notation,您可以为文档中特定索引或数组位置的字段指定查询条件。该数组使用基于零的索引。

Note

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

下面的示例选择所有包含instock数组作为其第一个元素的文档的文档,该文档包含字段qty的值小于或等于20

Mongo Shell
Compass
Python
Java (Sync)
Node.js
PHP
Motor
Java (Async)
C#
Perl
Ruby
Scala
db.inventory.find( { 'instock.0.qty': { $lte: 20 } } )

Copy the following filter into the Compass query bar and click Find:

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

为文档数组指定多个条件

在嵌套在文档数组中的多个字段上指定条件时,可以指定查询,以使单个文档满足这些条件,或者数组中文档的任意组合(包括单个文档)都满足条件。

单个嵌套文档在嵌套字段上满足多个查询条件

使用$elemMatch运算符可在一组嵌入式文档上指定多个条件,以使至少一个嵌入式文档满足所有指定条件。

下面的示例查询instock数组具有至少一个嵌入式文档的文档,这些文档同时包含等于5的字段qty和等于A的字段warehouse

Mongo Shell
Compass
Python
Java (Sync)
Node.js
PHP
Motor
Java (Async)
C#
Perl
Ruby
Scala
db.inventory.find( { "instock": { $elemMatch: { qty: 5, warehouse: "A" } } } )

Copy the following filter into the Compass query bar and click Find:

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

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

Mongo Shell
Compass
Python
Java (Sync)
Node.js
PHP
Motor
Java (Async)
C#
Perl
Ruby
Scala
db.inventory.find( { "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } } )

Copy the following filter into the Compass query bar and click Find:

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

元素组合满足条件

如果数组字段上的复合查询条件未使用$elemMatch运算符,则查询将选择其数组包含满足条件的元素的任意组合的那些文档。

例如,以下查询匹配文档,其中嵌套在instock数组中的任何文档的qty字段都大于10,并且数组中的任何文档(但不一定是同一嵌入式文档)的qty字段都小于或等于20

Mongo Shell
Compass
Python
Java (Sync)
Node.js
PHP
Motor
Java (Async)
C#
Perl
Ruby
Scala
db.inventory.find( { "instock.qty": { $gt: 10,  $lte: 20 } } )

Copy the following filter into the Compass query bar and click Find:

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

以下示例查询以下文档:instock数组具有至少一个包含等于5的字段qty的嵌入式文档和至少一个包含等于A的字段warehouse的嵌入式文档(但不一定是同一嵌入式文档):

Mongo Shell
Compass
Python
Java (Sync)
Node.js
PHP
Motor
Java (Async)
C#
Perl
Ruby
Scala
db.inventory.find( { "instock.qty": 5, "instock.warehouse": "A" } )

Copy the following filter into the Compass query bar and click Find:

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

其他查询教程

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