Query an Array of Embedded Documents
This page provides examples in:
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
This page provides examples of query operations on an array of nested documents using thedb.collection.find()
method in themongo
shell. The examples on this page use theinventory
collection. To populate the inventory
collection, run the following:
This page provides examples of query operations on an array of nested documents usingMongoDB Compass. The examples on thispage use the inventory
collection. Populate theinventory
collection with the following documents:
This page provides examples of query operations on an array of nested documents using thepymongo.collection.Collection.find()
method in thePyMongoPython driver. The examples on this page use the inventory
collection. To populate the inventory
collection, run thefollowing:
This page provides examples of query operations on an array of nested documents using thecom.mongodb.client.MongoCollection.find method in the MongoDBJava Synchronous Driver.
Tip
The driver provides com.mongodb.client.model.Filtershelper methods to facilitate the creation of filterdocuments. The examples on this page use these methods tocreate the filter documents.
The examples on this page use the inventory
collection. To populate the inventory
collection, run thefollowing:
This page provides examples of query operations on an array of nested documents using theCollection.find() method inthe MongoDB Node.js Driver.The examples on this page use the inventory
collection. Topopulate the inventory
collection, run the following:
This page provides examples of query operations on an array of nested documents using theMongoDB\Collection::find()
method in theMongoDB PHP Library.The examples on this page use the inventory
collection. Topopulate the inventory
collection, run the following:
This page provides examples of query operations on an array of nested documents using themotor.motor_asyncio.AsyncIOMotorCollection.find()
method in the Motordriver. The examples on this page use the inventory
collection. To populate the inventory
collection, run thefollowing:
This page provides examples of query operations on an array of nested documents using thecom.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 thefollowing:
This page provides examples of query operations on an array of nested documents using theMongoCollection.Find()method in theMongoDB C# Driver.The examples on this page use the inventory
collection. Topopulate the inventory
collection, run the following:
This page provides examples of query operations on an array of nested documents using theMongoDB::Collection::find() methodin theMongoDB Perl Driver.The examples on this page use the inventory
collection. Topopulate the inventory
collection, run the following:
This page provides examples of query operations on an array of nested documents using theMongo::Collection#find()method in theMongoDB Ruby Driver.The examples on this page use the inventory
collection. Topopulate the inventory
collection, run the following:
This page provides examples of query operations on an array of nested documents using thecollection.find()(implicite:org.mongodb.scala.bson.DefaultHelper.DefaultsTo[C,TResult],implicitct:scala.reflect.ClassTag[C]):org.mongodb.scala.FindObservable[C]) methodin theMongoDB Scala Driver.The examples on this page use the inventory
collection. Topopulate the inventory
collection, run the following:
This page provides examples of query operations on an array of nested documents using theCollection.Findfunction in theMongoDB Go Driver.The examples on this page use the inventory
collection. Topopulate the inventory
collection, run the following:
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
- 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:
- [
- { 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, seeInsert Documents.
- # 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 theinstock
array matches the specified document:
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
- db.inventory.find( { "instock": { warehouse: "A", qty: 5 } } )
Copy the following filter into the Compass query bar and clickFind:
- { "instock": { warehouse: "A", qty: 5 } }
- 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 anexact match of the specified document, including the field order. Forexample, the following query does not match any documents in theinventory
collection:
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
- db.inventory.find( { "instock": { qty: 5, warehouse: "A" } } )
- 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 thearray, concatenate the name of the array field, with a dot (.
) andthe name of the field in the nested document.
The following example selects all documents where the instock
arrayhas at least one embedded document that contains the field qty
whose value is less than or equal to 20
:
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
- db.inventory.find( { 'instock.qty': { $lte: 20 } } )
Copy the following filter into the Compass query bar and clickFind:
- { 'instock.qty': { $lte: 20 } }
- 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 forfield in a document at a particular index or position of the array. Thearray uses zero-based indexing.
Note
When querying using dot notation, the field and index must beinside quotation marks.
The following example selects all documents where the instock
arrayhas as its first element a document that contains the field qty
whose value is less than or equal to 20
:
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
- db.inventory.find( { 'instock.0.qty': { $lte: 20 } } )
Copy the following filter into the Compass query bar and clickFind:
- { 'instock.0.qty': { $lte: 20 } }
- 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 ofdocuments, you can specify the query such that either a single documentmeets these condition or any combination of documents (including asingle 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 anarray of embedded documents such that at least one embedded documentsatisfies all the specified criteria.
The following example queries for documents where the instock
arrayhas at least one embedded document that contains both the fieldqty
equal to 5
and the field warehouse
equalto A
:
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
- db.inventory.find( { "instock": { $elemMatch: { qty: 5, warehouse: "A" } } } )
Copy the following filter into the Compass query bar and clickFind:
- { "instock": { $elemMatch: { qty: 5, warehouse: "A" } } }
- 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
arrayhas at least one embedded document that contains the field qty
thatis greater than 10
and less than or equal to 20
:
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
- db.inventory.find( { "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } } )
Copy the following filter into the Compass query bar and clickFind:
- { "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } }
- 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 whosearray contains any combination of elements that satisfies theconditions.
For example, the following query matches documents where any documentnested in the instock
array has the qty
field greater than10
and any document (but not necessarily the same embeddeddocument) in the array has the qty
field less than or equal to20
:
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
- db.inventory.find( { "instock.qty": { $gt: 10, $lte: 20 } } )
Copy the following filter into the Compass query bar and clickFind:
- { "instock.qty": { $gt: 10, $lte: 20 } }
- 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
arrayhas at least one embedded document that contains the field qty
equal to 5
and at least one embedded document (but not necessarilythe same embedded document) that contains the field warehouse
equalto A
:
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
- Go
- db.inventory.find( { "instock.qty": 5, "instock.warehouse": "A" } )
Copy the following filter into the Compass query bar and clickFind:
- { "instock.qty": 5, "instock.warehouse": "A" }
- 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: