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 inventorycollection, 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 inventorycollection. 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 inventorycollection. 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 inventorycollection. 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 inventorycollection. 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
  1. db.inventory.insertMany( [
  2. { item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
  3. { item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
  4. { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
  5. { item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
  6. { item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
  7. ]);

You can run the operation in the web shell below:

  1. [
  2. { item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
  3. { item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
  4. { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
  5. { item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
  6. { item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
  7. ]

For instructions on inserting documents in MongoDB Compass, seeInsert Documents.

  1. # Subdocument key order matters in a few of these examples so we have
  2. # to use bson.son.SON instead of a Python dict.
  3. from bson.son import SON
  4. db.inventory.insert_many([
  5. {"item": "journal",
  6. "instock": [
  7. SON([("warehouse", "A"), ("qty", 5)]),
  8. SON([("warehouse", "C"), ("qty", 15)])]},
  9. {"item": "notebook",
  10. "instock": [
  11. SON([("warehouse", "C"), ("qty", 5)])]},
  12. {"item": "paper",
  13. "instock": [
  14. SON([("warehouse", "A"), ("qty", 60)]),
  15. SON([("warehouse", "B"), ("qty", 15)])]},
  16. {"item": "planner",
  17. "instock": [
  18. SON([("warehouse", "A"), ("qty", 40)]),
  19. SON([("warehouse", "B"), ("qty", 5)])]},
  20. {"item": "postcard",
  21. "instock": [
  22. SON([("warehouse", "B"), ("qty", 15)]),
  23. SON([("warehouse", "C"), ("qty", 35)])]}])
  1. collection.insertMany(asList(
  2. Document.parse("{ item: 'journal', instock: [ { warehouse: 'A', qty: 5 }, { warehouse: 'C', qty: 15 } ] }"),
  3. Document.parse("{ item: 'notebook', instock: [ { warehouse: 'C', qty: 5 } ] }"),
  4. Document.parse("{ item: 'paper', instock: [ { warehouse: 'A', qty: 60 }, { warehouse: 'B', qty: 15 } ] }"),
  5. Document.parse("{ item: 'planner', instock: [ { warehouse: 'A', qty: 40 }, { warehouse: 'B', qty: 5 } ] }"),
  6. Document.parse("{ item: 'postcard', instock: [ { warehouse: 'B', qty: 15 }, { warehouse: 'C', qty: 35 } ] }")
  7. ));
  1. await db.collection('inventory').insertMany([
  2. {
  3. item: 'journal',
  4. instock: [{ warehouse: 'A', qty: 5 }, { warehouse: 'C', qty: 15 }]
  5. },
  6. {
  7. item: 'notebook',
  8. instock: [{ warehouse: 'C', qty: 5 }]
  9. },
  10. {
  11. item: 'paper',
  12. instock: [{ warehouse: 'A', qty: 60 }, { warehouse: 'B', qty: 15 }]
  13. },
  14. {
  15. item: 'planner',
  16. instock: [{ warehouse: 'A', qty: 40 }, { warehouse: 'B', qty: 5 }]
  17. },
  18. {
  19. item: 'postcard',
  20. instock: [{ warehouse: 'B', qty: 15 }, { warehouse: 'C', qty: 35 }]
  21. }
  22. ]);
  1. $insertManyResult = $db->inventory->insertMany([
  2. [
  3. 'item' => 'journal',
  4. 'instock' => [
  5. ['warehouse' => 'A', 'qty' => 5],
  6. ['warehouse' => 'C', 'qty' => 15],
  7. ],
  8. ],
  9. [
  10. 'item' => 'notebook',
  11. 'instock' => [
  12. ['warehouse' => 'C', 'qty' => 5],
  13. ],
  14. ],
  15. [
  16. 'item' => 'paper',
  17. 'instock' => [
  18. ['warehouse' => 'A', 'qty' => 60],
  19. ['warehouse' => 'B', 'qty' => 15],
  20. ],
  21. ],
  22. [
  23. 'item' => 'planner',
  24. 'instock' => [
  25. ['warehouse' => 'A', 'qty' => 40],
  26. ['warehouse' => 'B', 'qty' => 5],
  27. ],
  28. ],
  29. [
  30. 'item' => 'postcard',
  31. 'instock' => [
  32. ['warehouse' => 'B', 'qty' => 15],
  33. ['warehouse' => 'C', 'qty' => 35],
  34. ],
  35. ],
  36. ]);
  1. # Subdocument key order matters in a few of these examples so we have
  2. # to use bson.son.SON instead of a Python dict.
  3. from bson.son import SON
  4. await db.inventory.insert_many([
  5. {"item": "journal",
  6. "instock": [
  7. SON([("warehouse", "A"), ("qty", 5)]),
  8. SON([("warehouse", "C"), ("qty", 15)])]},
  9. {"item": "notebook",
  10. "instock": [
  11. SON([("warehouse", "C"), ("qty", 5)])]},
  12. {"item": "paper",
  13. "instock": [
  14. SON([("warehouse", "A"), ("qty", 60)]),
  15. SON([("warehouse", "B"), ("qty", 15)])]},
  16. {"item": "planner",
  17. "instock": [
  18. SON([("warehouse", "A"), ("qty", 40)]),
  19. SON([("warehouse", "B"), ("qty", 5)])]},
  20. {"item": "postcard",
  21. "instock": [
  22. SON([("warehouse", "B"), ("qty", 15)]),
  23. SON([("warehouse", "C"), ("qty", 35)])]}])
  1. Publisher<Success> insertManyPublisher = collection.insertMany(asList(
  2. Document.parse("{ item: 'journal', instock: [ { warehouse: 'A', qty: 5 }, { warehouse: 'C', qty: 15 } ] }"),
  3. Document.parse("{ item: 'notebook', instock: [ { warehouse: 'C', qty: 5 } ] }"),
  4. Document.parse("{ item: 'paper', instock: [ { warehouse: 'A', qty: 60 }, { warehouse: 'B', qty: 15 } ] }"),
  5. Document.parse("{ item: 'planner', instock: [ { warehouse: 'A', qty: 40 }, { warehouse: 'B', qty: 5 } ] }"),
  6. Document.parse("{ item: 'postcard', instock: [ { warehouse: 'B', qty: 15 }, { warehouse: 'C', qty: 35 } ] }")
  7. ));
  1. var documents = new[]
  2. {
  3. new BsonDocument
  4. {
  5. { "item", "journal" },
  6. { "instock", new BsonArray
  7. {
  8. new BsonDocument { { "warehouse", "A" }, { "qty", 5 } },
  9. new BsonDocument { { "warehouse", "C" }, { "qty", 15 } } }
  10. }
  11. },
  12. new BsonDocument
  13. {
  14. { "item", "notebook" },
  15. { "instock", new BsonArray
  16. {
  17. new BsonDocument { { "warehouse", "C" }, { "qty", 5 } } }
  18. }
  19. },
  20. new BsonDocument
  21. {
  22. { "item", "paper" },
  23. { "instock", new BsonArray
  24. {
  25. new BsonDocument { { "warehouse", "A" }, { "qty", 60 } },
  26. new BsonDocument { { "warehouse", "B" }, { "qty", 15 } } }
  27. }
  28. },
  29. new BsonDocument
  30. {
  31. { "item", "planner" },
  32. { "instock", new BsonArray
  33. {
  34. new BsonDocument { { "warehouse", "A" }, { "qty", 40 } },
  35. new BsonDocument { { "warehouse", "B" }, { "qty", 5 } } }
  36. }
  37. },
  38. new BsonDocument
  39. {
  40. { "item", "postcard" },
  41. { "instock", new BsonArray
  42. {
  43. new BsonDocument { { "warehouse", "B" }, { "qty", 15 } },
  44. new BsonDocument { { "warehouse", "C" }, { "qty", 35 } } }
  45. }
  46. }
  47. };
  48. collection.InsertMany(documents);
  1. # Subdocument key order matters in this example so we have
  2. # to use Tie::IxHash instead of a regular, unordered Perl hash.
  3. $db->coll("inventory")->insert_many(
  4. [
  5. {
  6. item => "journal",
  7. instock => [
  8. Tie::IxHash->new( warehouse => "A", qty => 5 ),
  9. Tie::IxHash->new( warehouse => "C", qty => 15 )
  10. ]
  11. },
  12. {
  13. item => "notebook",
  14. instock => [ Tie::IxHash->new( warehouse => "C", qty => 5 ) ]
  15. },
  16. {
  17. item => "paper",
  18. instock => [
  19. Tie::IxHash->new( warehouse => "A", qty => 60 ),
  20. Tie::IxHash->new( warehouse => "B", qty => 15 )
  21. ]
  22. },
  23. {
  24. item => "planner",
  25. instock => [
  26. Tie::IxHash->new( warehouse => "A", qty => 40 ),
  27. Tie::IxHash->new( warehouse => "B", qty => 5 )
  28. ]
  29. },
  30. {
  31. item => "postcard",
  32. instock => [
  33. Tie::IxHash->new( warehouse => "B", qty => 15 ),
  34. Tie::IxHash->new( warehouse => "C", qty => 35 )
  35. ]
  36. }
  37. ]
  38. );
  1. client[:inventory].insert_many([{ item: 'journal',
  2. instock: [ { warehouse: 'A', qty: 5 },
  3. { warehouse: 'C', qty: 15 }] },
  4. { item: 'notebook',
  5. instock: [ { warehouse: 'C', qty: 5 }] },
  6. { item: 'paper',
  7. instock: [ { warehouse: 'A', qty: 60 },
  8. { warehouse: 'B', qty: 15 }] },
  9. { item: 'planner',
  10. instock: [ { warehouse: 'A', qty: 40 },
  11. { warehouse: 'B', qty: 5 }] },
  12. { item: 'postcard',
  13. instock: [ { warehouse: 'B', qty: 15 },
  14. { warehouse: 'C', qty: 35 }] }
  15. ])
  1. collection.insertMany(Seq(
  2. Document("""{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] }"""),
  3. Document("""{ item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] }"""),
  4. Document("""{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] }"""),
  5. Document("""{ item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] }"""),
  6. Document("""{ item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }""")
  7. )).execute()
  1. docs := []interface{}{
  2. bson.D{
  3. {"item", "journal"},
  4. {"instock", bson.A{
  5. bson.D{
  6. {"warehouse", "A"},
  7. {"qty", 5},
  8. },
  9. bson.D{
  10. {"warehouse", "C"},
  11. {"qty", 15},
  12. },
  13. }},
  14. },
  15. bson.D{
  16. {"item", "notebook"},
  17. {"instock", bson.A{
  18. bson.D{
  19. {"warehouse", "C"},
  20. {"qty", 5},
  21. },
  22. }},
  23. },
  24. bson.D{
  25. {"item", "paper"},
  26. {"instock", bson.A{
  27. bson.D{
  28. {"warehouse", "A"},
  29. {"qty", 60},
  30. },
  31. bson.D{
  32. {"warehouse", "B"},
  33. {"qty", 15},
  34. },
  35. }},
  36. },
  37. bson.D{
  38. {"item", "planner"},
  39. {"instock", bson.A{
  40. bson.D{
  41. {"warehouse", "A"},
  42. {"qty", 40},
  43. },
  44. bson.D{
  45. {"warehouse", "B"},
  46. {"qty", 5},
  47. },
  48. }},
  49. },
  50. bson.D{
  51. {"item", "postcard"},
  52. {"instock", bson.A{
  53. bson.D{
  54. {"warehouse", "B"},
  55. {"qty", 15},
  56. },
  57. bson.D{
  58. {"warehouse", "C"},
  59. {"qty", 35},
  60. },
  61. }},
  62. },
  63. }
  64.  
  65. 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
  1. db.inventory.find( { "instock": { warehouse: "A", qty: 5 } } )

Copy the following filter into the Compass query bar and clickFind:

  1. { "instock": { warehouse: "A", qty: 5 } }

../../_images/compass-find-nested-in-array.png

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

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
  1. db.inventory.find( { "instock": { qty: 5, warehouse: "A" } } )

../../_images/compass-find-nested-array-no-match.png

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

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 qtywhose 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
  1. db.inventory.find( { 'instock.qty': { $lte: 20 } } )

Copy the following filter into the Compass query bar and clickFind:

  1. { 'instock.qty': { $lte: 20 } }

../../_images/compass-find-array-embedded-field-condition.png

  1. cursor = db.inventory.find({'instock.qty': {"$lte": 20}})
  1. findIterable = collection.find(lte("instock.qty", 20));
  1. const cursor = db.collection('inventory').find({
  2. 'instock.qty': { $lte: 20 }
  3. });
  1. $cursor = $db->inventory->find(['instock.qty' => ['$lte' => 20]]);
  1. cursor = db.inventory.find({'instock.qty': {"$lte": 20}})
  1. findPublisher = collection.find(lte("instock.qty", 20));
  1. var filter = Builders<BsonDocument>.Filter.Lte("instock.qty", 20);
  2. var result = collection.Find(filter).ToList();
  1. $cursor = $db->coll("inventory")->find( { 'instock.qty' => { '$lte' => 20 } } );
  1. client[:inventory].find('instock.qty' => { '$lte' => 20 })
  1. findObservable = collection.find(lte("instock.qty", 20))
  1. cursor, err := coll.Find(
  2. context.Background(),
  3. bson.D{
  4. {"instock.qty", bson.D{
  5. {"$lte", 20},
  6. }},
  7. })

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 qtywhose 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
  1. db.inventory.find( { 'instock.0.qty': { $lte: 20 } } )

Copy the following filter into the Compass query bar and clickFind:

  1. { 'instock.0.qty': { $lte: 20 } }

../../_images/compass-find-array-index-embedded-doc.png

  1. cursor = db.inventory.find({'instock.0.qty': {"$lte": 20}})
  1. findIterable = collection.find(lte("instock.0.qty", 20));
  1. const cursor = db.collection('inventory').find({
  2. 'instock.0.qty': { $lte: 20 }
  3. });
  1. $cursor = $db->inventory->find(['instock.0.qty' => ['$lte' => 20]]);
  1. cursor = db.inventory.find({'instock.0.qty': {"$lte": 20}})
  1. findPublisher = collection.find(lte("instock.0.qty", 20));
  1. var filter = Builders<BsonDocument>.Filter.Lte("instock.0.qty", 20);
  2. var result = collection.Find(filter).ToList();
  1. $cursor = $db->coll("inventory")->find( { 'instock.0.qty' => { '$lte' => 20 } } );
  1. client[:inventory].find('instock.0.qty' => { '$lte' => 20 })
  1. findObservable = collection.find(lte("instock.0.qty", 20))
  1. cursor, err := coll.Find(
  2. context.Background(),
  3. bson.D{
  4. {"instock.0.qty", bson.D{
  5. {"$lte", 20},
  6. }},
  7. })

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
  1. db.inventory.find( { "instock": { $elemMatch: { qty: 5, warehouse: "A" } } } )

Copy the following filter into the Compass query bar and clickFind:

  1. { "instock": { $elemMatch: { qty: 5, warehouse: "A" } } }

../../_images/compass-array-multiple-cond-single-doc.png

  1. cursor = db.inventory.find(
  2. {"instock": {"$elemMatch": {"qty": 5, "warehouse": "A"}}})
  1. findIterable = collection.find(elemMatch("instock", Document.parse("{ qty: 5, warehouse: 'A' }")));
  1. const cursor = db.collection('inventory').find({
  2. instock: { $elemMatch: { qty: 5, warehouse: 'A' } }
  3. });
  1. $cursor = $db->inventory->find(['instock' => ['$elemMatch' => ['qty' => 5, 'warehouse' => 'A']]]);
  1. cursor = db.inventory.find(
  2. {"instock": {"$elemMatch": {"qty": 5, "warehouse": "A"}}})
  1. findPublisher = collection.find(elemMatch("instock", Document.parse("{ qty: 5, warehouse: 'A' }")));
  1. var filter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>("instock", new BsonDocument { { "qty", 5 }, { "warehouse", "A" } });
  2. var result = collection.Find(filter).ToList();
  1. $cursor = $db->coll("inventory")->find(
  2. { instock => { '$elemMatch' => { qty => 5, warehouse => "A" } } }
  3. );
  1. client[:inventory].find(instock: { '$elemMatch' => { qty: 5,
  2. warehouse: 'A' } })
  1. findObservable = collection.find(elemMatch("instock", Document("qty" -> 5, "warehouse" -> "A")))
  1. cursor, err := coll.Find(
  2. context.Background(),
  3. bson.D{
  4. {"instock", bson.D{
  5. {"$elemMatch", bson.D{
  6. {"qty", 5},
  7. {"warehouse", "A"},
  8. }},
  9. }},
  10. })

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
  1. db.inventory.find( { "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } } )

Copy the following filter into the Compass query bar and clickFind:

  1. { "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } }

../../_images/compass-array-multiple-cond-single-doc-2.png

  1. cursor = db.inventory.find(
  2. {"instock": {"$elemMatch": {"qty": {"$gt": 10, "$lte": 20}}}})
  1. findIterable = collection.find(elemMatch("instock", Document.parse("{ qty: { $gt: 10, $lte: 20 } }")));
  1. const cursor = db.collection('inventory').find({
  2. instock: { $elemMatch: { qty: { $gt: 10, $lte: 20 } } }
  3. });
  1. $cursor = $db->inventory->find(['instock' => ['$elemMatch' => ['qty' => ['$gt' => 10, '$lte' => 20]]]]);
  1. cursor = db.inventory.find(
  2. {"instock": {"$elemMatch": {"qty": {"$gt": 10, "$lte": 20}}}})
  1. findPublisher = collection.find(elemMatch("instock", Document.parse("{ qty: { $gt: 10, $lte: 20 } }")));
  1. var filter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>("instock", new BsonDocument { { "qty", new BsonDocument { { "$gt", 10 }, { "$lte", 20 } } } });
  2. var result = collection.Find(filter).ToList();
  1. $cursor = $db->coll("inventory") ->find(
  2. { instock => { '$elemMatch' => { qty => { '$gt' => 10, '$lte' => 20 } } } }
  3. );
  1. client[:inventory].find(instock: { '$elemMatch' => { qty: { '$gt' => 10,
  2. '$lte' => 20 } } })
  1. findObservable = collection.find(elemMatch("instock", Document("""{ qty: { $gt: 10, $lte: 20 } }""")))
  1. cursor, err := coll.Find(
  2. context.Background(),
  3. bson.D{
  4. {"instock", bson.D{
  5. {"$elemMatch", bson.D{
  6. {"qty", bson.D{
  7. {"$gt", 10},
  8. {"$lte", 20},
  9. }},
  10. }},
  11. }},
  12. })

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
  1. db.inventory.find( { "instock.qty": { $gt: 10, $lte: 20 } } )

Copy the following filter into the Compass query bar and clickFind:

  1. { "instock.qty": { $gt: 10, $lte: 20 } }

../../_images/compass-array-match-combination-of-elements.png

  1. cursor = db.inventory.find({"instock.qty": {"$gt": 10, "$lte": 20}})
  1. findIterable = collection.find(and(gt("instock.qty", 10), lte("instock.qty", 20)));
  1. const cursor = db.collection('inventory').find({
  2. 'instock.qty': { $gt: 10, $lte: 20 }
  3. });
  1. $cursor = $db->inventory->find(['instock.qty' => ['$gt' => 10, '$lte' => 20]]);
  1. cursor = db.inventory.find({"instock.qty": {"$gt": 10, "$lte": 20}})
  1. findPublisher = collection.find(and(gt("instock.qty", 10), lte("instock.qty", 20)));
  1. var builder = Builders<BsonDocument>.Filter;
  2. var filter = builder.And(builder.Gt("instock.qty", 10), builder.Lte("instock.qty", 20));
  3. var result = collection.Find(filter).ToList();
  1. $cursor = $db->coll("inventory")->find(
  2. { "instock.qty" => { '$gt' => 10, '$lte' => 20 } }
  3. );
  1. client[:inventory].find('instock.qty' => { '$gt' => 10, '$lte' => 20 })
  1. findObservable = collection.find(and(gt("instock.qty", 10), lte("instock.qty", 20)))
  1. cursor, err := coll.Find(
  2. context.Background(),
  3. bson.D{
  4. {"instock.qty", bson.D{
  5. {"$gt", 10},
  6. {"$lte", 20},
  7. }},
  8. })

The following example queries for documents where the instock arrayhas at least one embedded document that contains the field qtyequal 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
  1. db.inventory.find( { "instock.qty": 5, "instock.warehouse": "A" } )

Copy the following filter into the Compass query bar and clickFind:

  1. { "instock.qty": 5, "instock.warehouse": "A" }

../../_images/compass-array-match-combination-of-elements-2.png

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

Additional Query Tutorials

For additional query examples, see: