Query on Embedded/Nested 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 embedded/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 embedded/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 embedded/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 embedded/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 embedded/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 embedded/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 embedded/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 embedded/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 embedded/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 embedded/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 embedded/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 embedded/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 embedded/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", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
  3. { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
  4. { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
  5. { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
  6. { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
  7. ]);

You can run the operation in the web shell below:

  1. [
  2. { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
  3. { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
  4. { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
  5. { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
  6. { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
  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. "qty": 25,
  7. "size": SON([("h", 14), ("w", 21), ("uom", "cm")]),
  8. "status": "A"},
  9. {"item": "notebook",
  10. "qty": 50,
  11. "size": SON([("h", 8.5), ("w", 11), ("uom", "in")]),
  12. "status": "A"},
  13. {"item": "paper",
  14. "qty": 100,
  15. "size": SON([("h", 8.5), ("w", 11), ("uom", "in")]),
  16. "status": "D"},
  17. {"item": "planner",
  18. "qty": 75,
  19. "size": SON([("h", 22.85), ("w", 30), ("uom", "cm")]),
  20. "status": "D"},
  21. {"item": "postcard",
  22. "qty": 45,
  23. "size": SON([("h", 10), ("w", 15.25), ("uom", "cm")]),
  24. "status": "A"}])
  1. collection.insertMany(asList(
  2. Document.parse("{ item: 'journal', qty: 25, size: { h: 14, w: 21, uom: 'cm' }, status: 'A' }"),
  3. Document.parse("{ item: 'notebook', qty: 50, size: { h: 8.5, w: 11, uom: 'in' }, status: 'A' }"),
  4. Document.parse("{ item: 'paper', qty: 100, size: { h: 8.5, w: 11, uom: 'in' }, status: 'D' }"),
  5. Document.parse("{ item: 'planner', qty: 75, size: { h: 22.85, w: 30, uom: 'cm' }, status: 'D' }"),
  6. Document.parse("{ item: 'postcard', qty: 45, size: { h: 10, w: 15.25, uom: 'cm' }, status: 'A' }")
  7. ));
  1. await db.collection('inventory').insertMany([
  2. {
  3. item: 'journal',
  4. qty: 25,
  5. size: { h: 14, w: 21, uom: 'cm' },
  6. status: 'A'
  7. },
  8. {
  9. item: 'notebook',
  10. qty: 50,
  11. size: { h: 8.5, w: 11, uom: 'in' },
  12. status: 'A'
  13. },
  14. {
  15. item: 'paper',
  16. qty: 100,
  17. size: { h: 8.5, w: 11, uom: 'in' },
  18. status: 'D'
  19. },
  20. {
  21. item: 'planner',
  22. qty: 75,
  23. size: { h: 22.85, w: 30, uom: 'cm' },
  24. status: 'D'
  25. },
  26. {
  27. item: 'postcard',
  28. qty: 45,
  29. size: { h: 10, w: 15.25, uom: 'cm' },
  30. status: 'A'
  31. }
  32. ]);
  1. $insertManyResult = $db->inventory->insertMany([
  2. [
  3. 'item' => 'journal',
  4. 'qty' => 25,
  5. 'size' => ['h' => 14, 'w' => 21, 'uom' => 'cm'],
  6. 'status' => 'A',
  7. ],
  8. [
  9. 'item' => 'notebook',
  10. 'qty' => 50,
  11. 'size' => ['h' => 8.5, 'w' => 11, 'uom' => 'in'],
  12. 'status' => 'A',
  13. ],
  14. [
  15. 'item' => 'paper',
  16. 'qty' => 100,
  17. 'size' => ['h' => 8.5, 'w' => 11, 'uom' => 'in'],
  18. 'status' => 'D',
  19. ],
  20. [
  21. 'item' => 'planner',
  22. 'qty' => 75,
  23. 'size' => ['h' => 22.85, 'w' => 30, 'uom' => 'cm'],
  24. 'status' => 'D',
  25. ],
  26. [
  27. 'item' => 'postcard',
  28. 'qty' => 45,
  29. 'size' => ['h' => 10, 'w' => 15.25, 'uom' => 'cm'],
  30. 'status' => 'A',
  31. ],
  32. ]);
  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. "qty": 25,
  7. "size": SON([("h", 14), ("w", 21), ("uom", "cm")]),
  8. "status": "A"},
  9. {"item": "notebook",
  10. "qty": 50,
  11. "size": SON([("h", 8.5), ("w", 11), ("uom", "in")]),
  12. "status": "A"},
  13. {"item": "paper",
  14. "qty": 100,
  15. "size": SON([("h", 8.5), ("w", 11), ("uom", "in")]),
  16. "status": "D"},
  17. {"item": "planner",
  18. "qty": 75,
  19. "size": SON([("h", 22.85), ("w", 30), ("uom", "cm")]),
  20. "status": "D"},
  21. {"item": "postcard",
  22. "qty": 45,
  23. "size": SON([("h", 10), ("w", 15.25), ("uom", "cm")]),
  24. "status": "A"}])
  1. Publisher<Success> insertManyPublisher = collection.insertMany(asList(
  2. Document.parse("{ item: 'journal', qty: 25, size: { h: 14, w: 21, uom: 'cm' }, status: 'A' }"),
  3. Document.parse("{ item: 'notebook', qty: 50, size: { h: 8.5, w: 11, uom: 'in' }, status: 'A' }"),
  4. Document.parse("{ item: 'paper', qty: 100, size: { h: 8.5, w: 11, uom: 'in' }, status: 'D' }"),
  5. Document.parse("{ item: 'planner', qty: 75, size: { h: 22.85, w: 30, uom: 'cm' }, status: 'D' }"),
  6. Document.parse("{ item: 'postcard', qty: 45, size: { h: 10, w: 15.25, uom: 'cm' }, status: 'A' }")
  7. ));
  1. var documents = new[]
  2. {
  3. new BsonDocument
  4. {
  5. { "item", "journal" },
  6. { "qty", 25 },
  7. { "size", new BsonDocument { { "h", 14 }, { "w", 21 }, { "uom", "cm" } } },
  8. { "status", "A" }
  9. },
  10. new BsonDocument
  11. {
  12. { "item", "notebook" },
  13. { "qty", 50 },
  14. { "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in" } } },
  15. { "status", "A" }
  16. },
  17. new BsonDocument
  18. {
  19. { "item", "paper" },
  20. { "qty", 100 },
  21. { "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in" } } },
  22. { "status", "D" }
  23. },
  24. new BsonDocument
  25. {
  26. { "item", "planner" },
  27. { "qty", 75 },
  28. { "size", new BsonDocument { { "h", 22.85 }, { "w", 30 }, { "uom", "cm" } } },
  29. { "status", "D" }
  30. },
  31. new BsonDocument
  32. {
  33. { "item", "postcard" },
  34. { "qty", 45 },
  35. { "size", new BsonDocument { { "h", 10 }, { "w", 15.25 }, { "uom", "cm" } } },
  36. { "status", "A" } },
  37. };
  38. 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. qty => 25,
  8. size => Tie::IxHash->new( h => 14, w => 21, uom => "cm" ),
  9. status => "A"
  10. },
  11. {
  12. item => "notebook",
  13. qty => 50,
  14. size => Tie::IxHash->new( h => 8.5, w => 11, uom => "in" ),
  15. status => "A"
  16. },
  17. {
  18. item => "paper",
  19. qty => 100,
  20. size => Tie::IxHash->new( h => 8.5, w => 11, uom => "in" ),
  21. status => "D"
  22. },
  23. {
  24. item => "planner",
  25. qty => 75,
  26. size => Tie::IxHash->new( h => 22.85, w => 30, uom => "cm" ),
  27. status => "D"
  28. },
  29. {
  30. item => "postcard",
  31. qty => 45,
  32. size => Tie::IxHash->new( h => 10, w => 15.25, uom => "cm" ),
  33. status => "A"
  34. }
  35. ]
  36. );
  1. client[:inventory].insert_many([
  2. { item: 'journal',
  3. qty: 25,
  4. size: { h: 14, w: 21, uom: 'cm' },
  5. status: 'A' },
  6. { item: 'notebook',
  7. qty: 50,
  8. size: { h: 8.5, w: 11, uom: 'in' },
  9. status: 'A' },
  10. { item: 'paper',
  11. qty: 100,
  12. size: { h: 8.5, w: 11, uom: 'in' },
  13. status: 'D' },
  14. { item: 'planner',
  15. qty: 75,
  16. size: { h: 22.85, w: 30, uom: 'cm' },
  17. status: 'D' },
  18. { item: 'postcard',
  19. qty: 45,
  20. size: { h: 10, w: 15.25, uom: 'cm' },
  21. status: 'A' }
  22. ])
  1. collection.insertMany(Seq(
  2. Document("""{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" }"""),
  3. Document("""{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" }"""),
  4. Document("""{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" }"""),
  5. Document("""{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" }"""),
  6. Document("""{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }""")
  7. )).execute()
  1. docs := []interface{}{
  2. bson.D{
  3. {"item", "journal"},
  4. {"qty", 25},
  5. {"size", bson.D{
  6. {"h", 14},
  7. {"w", 21},
  8. {"uom", "cm"},
  9. }},
  10. {"status", "A"},
  11. },
  12. bson.D{
  13. {"item", "notebook"},
  14. {"qty", 50},
  15. {"size", bson.D{
  16. {"h", 8.5},
  17. {"w", 11},
  18. {"uom", "in"},
  19. }},
  20. {"status", "A"},
  21. },
  22. bson.D{
  23. {"item", "paper"},
  24. {"qty", 100},
  25. {"size", bson.D{
  26. {"h", 8.5},
  27. {"w", 11},
  28. {"uom", "in"},
  29. }},
  30. {"status", "D"},
  31. },
  32. bson.D{
  33. {"item", "planner"},
  34. {"qty", 75},
  35. {"size", bson.D{
  36. {"h", 22.85},
  37. {"w", 30},
  38. {"uom", "cm"},
  39. }},
  40. {"status", "D"},
  41. },
  42. bson.D{
  43. {"item", "postcard"},
  44. {"qty", 45},
  45. {"size", bson.D{
  46. {"h", 10},
  47. {"w", 15.25},
  48. {"uom", "cm"},
  49. }},
  50. {"status", "A"},
  51. },
  52. }
  53.  
  54. result, err := coll.InsertMany(context.Background(), docs)

Match an Embedded/Nested Document

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

To specify an equality condition on a field that is anembedded/nested document, use thequery filter document{ <field>: <value> } where <value> is the documentto match.

To specify an equality condition on a field that is anembedded/nested document, use thequery filter document{ <field>: <value> } where <value> is the documentto match.

To specify an equality condition on a field that is anembedded/nested document, use thequery filter document{ <field>: <value> } where <value> is the documentto match.

To specify an equality condition on a field that is anembedded/nested document, use the filter documenteq( <field1>, <value>) where <value> is the documentto match.

To specify an equality condition on a field that is anembedded/nested document, use thequery filter document{ <field>: <value> } where <value> is the documentto match.

To specify an equality condition on a field that is anembedded/nested document, use thequery filter document[ <field> => <value> ] where <value> is the documentto match.

To specify an equality condition on a field that is anembedded/nested document, use thequery filter document{ <field>: <value> } where <value> is the documentto match.

To specify an equality condition on a field that is anembedded/nested document, use the filter documenteq( <field1>, <value>) where <value> is the documentto match.

To specify an equality condition on a field that is anembedded/nested document, construct a filter using theEqmethod:

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

<value> is the document to match.

To specify an equality condition on a field that is anembedded/nested document, use thequery filter document{ <field> => <value> } where <value> is the documentto match.

To specify an equality condition on a field that is anembedded/nested document, use thequery filter document{ <field> => <value> } where <value> is the documentto match.

To specify an equality condition on a field that is anembedded/nested document, use the filter documentequal( <field1>, <value> ) where <value> is the documentto match.

For example, the following query selects all documents where the fieldsize equals the document { h: 14, w: 21, uom: "cm" }:

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )

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

  1. { size: { h: 14, w: 21, uom: "cm" } }

../../_images/compass-match-embedded.png

  1. cursor = db.inventory.find(
  2. {"size": SON([("h", 14), ("w", 21), ("uom", "cm")])})
  1. FindIterable<Document> findIterable = collection.find(eq("size", Document.parse("{ h: 14, w: 21, uom: 'cm' }")));
  1. const cursor = db.collection('inventory').find({
  2. size: { h: 14, w: 21, uom: 'cm' }
  3. });
  1. $cursor = $db->inventory->find(['size' => ['h' => 14, 'w' => 21, 'uom' => 'cm']]);
  1. cursor = db.inventory.find(
  2. {"size": SON([("h", 14), ("w", 21), ("uom", "cm")])})
  1. FindPublisher<Document> findPublisher = collection.find(eq("size", Document.parse("{ h: 14, w: 21, uom: 'cm' }")));
  1. var filter = Builders<BsonDocument>.Filter.Eq("size", new BsonDocument { { "h", 14 }, { "w", 21 }, { "uom", "cm" } });
  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. { size => Tie::IxHash->new( h => 14, w => 21, uom => "cm" ) }
  5. );
  1. client[:inventory].find(size: { h: 14, w: 21, uom: 'cm' })
  1. var findObservable = collection.find(equal("size", Document("h" -> 14, "w" -> 21, "uom" -> "cm")))
  1. cursor, err := coll.Find(
  2. context.Background(),
  3. bson.D{
  4. {"size", bson.D{
  5. {"h", 14},
  6. {"w", 21},
  7. {"uom", "cm"},
  8. }},
  9. })

Equality matches on the whole embedded document require an _exact_match of the specified <value> document, including the field order.For example, 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( { size: { w: 21, h: 14, uom: "cm" } } )

../../_images/compass-find-embedded-no-match.png

  1. cursor = db.inventory.find(
  2. {"size": SON([("w", 21), ("h", 14), ("uom", "cm")])})
  1. findIterable = collection.find(eq("size", Document.parse("{ w: 21, h: 14, uom: 'cm' }")));
  1. const cursor = db.collection('inventory').find({
  2. size: { w: 21, h: 14, uom: 'cm' }
  3. });
  1. $cursor = $db->inventory->find(['size' => ['w' => 21, 'h' => 14, 'uom' => 'cm']]);
  1. cursor = db.inventory.find(
  2. {"size": SON([("w", 21), ("h", 14), ("uom", "cm")])})
  1. findPublisher = collection.find(eq("size", Document.parse("{ w: 21, h: 14, uom: 'cm' }")));
  1. var filter = Builders<BsonDocument>.Filter.Eq("size", new BsonDocument { { "w", 21 }, { "h", 14 }, { "uom", "cm" } });
  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. { size => Tie::IxHash->new( w => 21, h => 14, uom => "cm" ) }
  5. );
  1. client[:inventory].find(size: { h: 21, w: 14, uom: 'cm' })
  1. findObservable = collection.find(equal("size", Document("w" -> 21, "h" -> 14, "uom" -> "cm")))
  1. cursor, err := coll.Find(
  2. context.Background(),
  3. bson.D{
  4. {"size", bson.D{
  5. {"w", 21},
  6. {"h", 14},
  7. {"uom", "cm"},
  8. }},
  9. })

Query on Nested Field

To specify a query condition on fields in an embedded/nested document,use dot notation ("field.nestedField").

Note

When querying using dot notation, the field and nested field must beinside quotation marks.

Specify Equality Match on a Nested Field

The following example selects all documents where the field uomnested in the size field equals "in":

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { "size.uom": "in" } )

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

  1. { "size.uom": "in" }

../../_images/compass-find-nested-field.png

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

Specify Match using Query Operator

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

A query filter document canuse the query operators to specifyconditions in the following form:

  1. { <field1>: { <operator1>: <value1> }, ... }

A query filter document canuse the query operators to specifyconditions in the following form:

  1. { <field1>: { <operator1>: <value1> }, ... }

A query filter document canuse the query operators to specifyconditions in the following form:

  1. { <field1>: { <operator1>: <value1> }, ... }

In addition to the equality condition, MongoDB providesvarious query operators to specifyfilter conditions. Use thecom.mongodb.client.model.Filters helper methods tofacilitate the creation of filter documents. For example:

  1. and(gte(<field1>, <value1>), lt(<field2>, <value2>), eq(<field3>, <value3>))

A query filter document canuse the query operators to specifyconditions in the following form:

  1. { <field1>: { <operator1>: <value1> }, ... }

A query filter document canuse the query operators to specifyconditions in the following form:

  1. [ <field1> => [ <operator1> => <value1> ], ... ]

A query filter document canuse the query operators to specifyconditions in the following form:

  1. { <field1>: { <operator1>: <value1> }, ... }

In addition to the equality condition, MongoDB providesvarious query operators to specifyfilter conditions. Use thecom.mongodb.client.model.Filters helper methods tofacilitate the creation of filter documents. For example:

  1. and(gte(<field1>, <value1>), lt(<field2>, <value2>), eq(<field3>, <value3>))

In addition to the equality filter, MongoDB providesvarious query operators to specifyfilter conditions. Use theFilterDefinitionBuildermethods to create a filter document. For example:

  1. var builder = Builders<BsonDocument>.Filter;
  2. builder.And(builder.Eq(<field1>, <value1>), builder.Lt(<field2>, <value2>));

A query filter document canuse the query operators to specifyconditions in the following form:

  1. { <field1> => { <operator1> => <value1> }, ... }

A query filter document canuse the query operators to specifyconditions in the following form:

  1. { <field1> => { <operator1> => <value1> }, ... }

In addition to the equality condition, MongoDB providesvarious query operators to specifyfilter conditions. Use thecom.mongodb.client.model.Filters_ helper methods tofacilitate the creation of filter documents. For example:

  1. and(gte(<field1>, <value1>), lt(<field2>, <value2>), equal(<field3>, <value3>))

The following query uses the less than operator ($lt) onthe field h embedded in the size field:

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { "size.h": { $lt: 15 } } )

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

  1. { "size.h": { $lt: 15 } }

../../_images/compass-find-nested-query-op.png

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

Specify AND Condition

The following query selects all documents where the nested field his less than 15, the nested field uom equals "in", and thestatus field equals "D":

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { "size.h": { $lt: 15 }, "size.uom": "in", status: "D" } )

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

  1. { "size.h": { $lt: 15 }, "size.uom": "in", status: "D" }

../../_images/compass-find-embedded-and.png

  1. cursor = db.inventory.find(
  2. {"size.h": {"$lt": 15}, "size.uom": "in", "status": "D"})
  1. findIterable = collection.find(and(
  2. lt("size.h", 15),
  3. eq("size.uom", "in"),
  4. eq("status", "D")
  5. ));
  1. const cursor = db.collection('inventory').find({
  2. 'size.h': { $lt: 15 },
  3. 'size.uom': 'in',
  4. status: 'D'
  5. });
  1. $cursor = $db->inventory->find([
  2. 'size.h' => ['$lt' => 15],
  3. 'size.uom' => 'in',
  4. 'status' => 'D',
  5. ]);
  1. cursor = db.inventory.find(
  2. {"size.h": {"$lt": 15}, "size.uom": "in", "status": "D"})
  1. findPublisher = collection.find(and(
  2. lt("size.h", 15),
  3. eq("size.uom", "in"),
  4. eq("status", "D")
  5. ));
  1. var builder = Builders<BsonDocument>.Filter;
  2. var filter = builder.And(builder.Lt("size.h", 15), builder.Eq("size.uom", "in"), builder.Eq("status", "D"));
  3. var result = collection.Find(filter).ToList();
  1. $cursor = $db->coll("inventory")->find(
  2. { "size.h" => { '$lt' => 15 }, "size.uom" => "in", status => "D" }
  3. );
  1. client[:inventory].find('size.h' => { '$lt' => 15 },
  2. 'size.uom' => 'in',
  3. 'status' => 'D')
  1. findObservable = collection.find(and(
  2. lt("size.h", 15),
  3. equal("size.uom", "in"),
  4. equal("status", "D")
  5. ))
  1. cursor, err := coll.Find(
  2. context.Background(),
  3. bson.D{
  4. {"size.h", bson.D{
  5. {"$lt", 15},
  6. }},
  7. {"size.uom", "in"},
  8. {"status", "D"},
  9. })

Additional Query Tutorials

For additional query examples, see: