Query 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 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 usingMongoDB Compass. The examples on thispage use the inventory collection. Populate theinventory collection with the following documents:

This page provides examples of query operations 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 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 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 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 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 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 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 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 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 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 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. db.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, "size": {"h": 22.85, "w": 30, "uom": "cm"},
  16. "status": "D"},
  17. {"item": "postcard",
  18. "qty": 45,
  19. "size": {"h": 10, "w": 15.25, "uom": "cm"},
  20. "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. await db.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, "size": {"h": 22.85, "w": 30, "uom": "cm"},
  16. "status": "D"},
  17. {"item": "postcard",
  18. "qty": 45,
  19. "size": {"h": 10, "w": 15.25, "uom": "cm"},
  20. "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 BsonDocument[]
  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. };
  39. collection.InsertMany(documents);
  1. $db->coll("inventory")->insert_many(
  2. [
  3. {
  4. item => "journal",
  5. qty => 25,
  6. size => { h => 14, w => 21, uom => "cm" },
  7. status => "A"
  8. },
  9. {
  10. item => "notebook",
  11. qty => 50,
  12. size => { h => 8.5, w => 11, uom => "in" },
  13. status => "A"
  14. },
  15. {
  16. item => "paper",
  17. qty => 100,
  18. size => { h => 8.5, w => 11, uom => "in" },
  19. status => "D"
  20. },
  21. {
  22. item => "planner",
  23. qty => 75,
  24. size => { h => 22.85, w => 30, uom => "cm" },
  25. status => "D"
  26. },
  27. {
  28. item => "postcard",
  29. qty => 45,
  30. size => { h => 10, w => 15.25, uom => "cm" },
  31. status => "A"
  32. }
  33. ]
  34. );
  1. client[:inventory].insert_many([{ item: 'journal',
  2. qty: 25,
  3. size: { h: 14, w: 21, uom: 'cm' },
  4. status: 'A' },
  5. { item: 'notebook',
  6. qty: 50,
  7. size: { h: 8.5, w: 11, uom: 'in' },
  8. status: 'A' },
  9. { item: 'paper',
  10. qty: 100,
  11. size: { h: 8.5, w: 11, uom: 'in' },
  12. status: 'D' },
  13. { item: 'planner',
  14. qty: 75,
  15. size: { h: 22.85, w: 30, uom: 'cm' },
  16. status: 'D' },
  17. { item: 'postcard',
  18. qty: 45,
  19. size: { h: 10, w: 15.25, uom: 'cm' },
  20. status: 'A' }
  21. ])
  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)

Select All Documents in a Collection

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

To select all documents in the collection, pass an emptydocument as the query filter parameter to the find method. Thequery filter parameter determines the select criteria:

To select all documents in the collection, pass an emptydocument as the query filter parameter to thequery bar. Thequery filter parameter determinesthe select criteria:

To select all documents in the collection, pass an emptydocument as the query filter parameter to the find method. Thequery filter parameter determines the select criteria:

To select all documents in the collection, pass an emptydocument as the query filter parameter to the find method. Thequery filter parameter determines the select criteria:

To select all documents in the collection, pass an emptydocument as the query filter parameter to the find method. Thequery filter parameter determines the select criteria:

To select all documents in the collection, pass an emptydocument as the query filter parameter to the find method. Thequery filter parameter determines the select criteria:

To select all documents in the collection, pass an emptydocument as the query filter parameter to the find method. Thequery filter parameter determines the select criteria:

To select all documents in the collection, pass an emptydocument as the query filter parameter to the find method. Thequery filter parameter determines the select criteria:

To select all documents in the collection, pass an emptydocument as the query filter parameter to the find method. Thequery filter parameter determines the select criteria:

To select all documents in the collection, pass an emptydocument as the query filter parameter to the find method. Thequery filter parameter determines the select criteria:

To select all documents in the collection, pass an emptydocument as the query filter parameter to the find method. Thequery filter parameter determines the select criteria:

To select all documents in the collection, pass an emptydocument as the query filter parameter to the find method. Thequery filter parameter determines the select criteria:

To select all documents in the collection, pass an emptydocument as the query filter parameter to the find method. Thequery filter parameter determines the select criteria:

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

../../_images/compass-select-all.png

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

This operation corresponds to the following SQL statement:

  1. SELECT * FROM inventory
  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala

For more information on the syntax of the method, seefind().

For more information on the MongoDB Compass query bar, seeQuery Bar.

For more information on the syntax of the method, seefind().

For more information on the syntax of the method, seecom.mongodb.client.MongoCollection.find.

For more information on the syntax of the method, seefind().

For more information on the syntax of the method, seefind().

For more information on the syntax of the method, seecom.mongodb.reactivestreams.client.MongoCollection.find).

For more information on the syntax of the method, seeFind().

For more information on the syntax of the method, seefind().

For more information on the syntax of the method, seefind().

For more information on the syntax of the method, seecollection.find()(implicite:org.mongodb.scala.bson.DefaultHelper.DefaultsTo[C,TResult],implicitct:scala.reflect.ClassTag[C]):org.mongodb.scala.FindObservable[C]).

Specify Equality Condition

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

To specify equality conditions, use <field>:<value>expressions in thequery filter document:

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

To specify equality conditions, use <field>:<value>expressions in thequery filter document:

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

To specify equality conditions, use <field>:<value>expressions in thequery filter document:

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

To specify equality conditions, use thecom.mongodb.client.model.Filters.eq_ method to create thequery filter document:

  1. and(eq( <field1>, <value1>), eq( <field2>, <value2>) ...)

To specify equality conditions, use <field>:<value>expressions in thequery filter document:

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

To specify equality conditions, use <field> => <value>expressions in thequery filter document:

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

To specify equality conditions, use <field>:<value>expressions in thequery filter document:

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

To specify equality conditions, use thecom.mongodb.client.model.Filters.eq method to create thequery filter document:

  1. and(eq( <field1>, <value1>), eq( <field2>, <value2>) ...)

To specify equality conditions, construct a filter using theEq method:

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

To specify equality conditions, use <field> => <value>expressions in thequery filter document:

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

To specify equality conditions, use <field> => <value>expressions in thequery filter document:

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

To specify equality conditions, use thecom.mongodb.client.model.Filters.eq_ method to create thequery filter document:

  1. and(equal(<field1>, <value1>), equal(<field2>, <value2>) ...)

The following example selects from the inventory collection alldocuments where the status equals "D":

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

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

  1. { status: "D" }

../../_images/compass-find-filter-inventory.png

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

This operation corresponds to the following SQL statement:

  1. SELECT * FROM inventory WHERE status = "D"
  • Compass

Note

The MongoDB Compass query bar autocompletes the current querybased on the keys in your collection’s documents, includingkeys in embedded sub-documents.

Specify Conditions Using Query Operators

  • 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 example retrieves all documents from the inventorycollection where status equals either "A" or "D":

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

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

  1. { status: { $in: [ "A", "D" ] } }

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

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

Note

Although you can express this query using the $or operator,use the $in operator rather than the $oroperator when performing equality checks on the same field.

The operation corresponds to the following SQL statement:

  1. SELECT * FROM inventory WHERE status in ("A", "D")

Refer to the Query and Projection Operators document for the completelist of MongoDB query operators.

Specify AND Conditions

A compound query can specify conditions for more than one field in thecollection’s documents. Implicitly, a logical AND conjunctionconnects the clauses of a compound query so that the query selects thedocuments in the collection that match all the conditions.

The following example retrieves all documents in the inventorycollection where the status equals "A" and qty is lessthan ($lt) 30:

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

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

  1. { status: "A", qty: { $lt: 30 } }

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

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

The operation corresponds to the following SQL statement:

  1. SELECT * FROM inventory WHERE status = "A" AND qty < 30

See comparison operators for otherMongoDB comparison operators.

Specify OR Conditions

Using the $or operator, you can specify a compound querythat joins each clause with a logical OR conjunction so that thequery selects the documents in the collection that match at least onecondition.

The following example retrieves all documents in the collection wherethe status equals "A" or qty is less than($lt) 30:

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )

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

  1. { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] }

../../_images/compass-find-filter-or.png

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

The operation corresponds to the following SQL statement:

  1. SELECT * FROM inventory WHERE status = "A" OR qty < 30

Note

Queries which use comparison operatorsare subject to Type Bracketing.

Specify AND as well as OR Conditions

In the following example, the compound query document selects alldocuments in the collection where the status equals "A"andeither qty is less than ($lt) 30 oritem starts with the character p:

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( {
  2. status: "A",
  3. $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]
  4. } )

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

  1. { status: "A", $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ] }

../../_images/compass-find-filter-and-or.png

  1. cursor = db.inventory.find({
  2. "status": "A",
  3. "$or": [{"qty": {"$lt": 30}}, {"item": {"$regex": "^p"}}]})
  1. findIterable = collection.find(
  2. and(eq("status", "A"),
  3. or(lt("qty", 30), regex("item", "^p")))
  4. );
  1. const cursor = db.collection('inventory').find({
  2. status: 'A',
  3. $or: [{ qty: { $lt: 30 } }, { item: { $regex: '^p' } }]
  4. });
  1. $cursor = $db->inventory->find([
  2. 'status' => 'A',
  3. '$or' => [
  4. ['qty' => ['$lt' => 30]],
  5. // Alternatively: ['item' => new \MongoDB\BSON\Regex('^p')]
  6. ['item' => ['$regex' => '^p']],
  7. ],
  8. ]);
  1. cursor = db.inventory.find({
  2. "status": "A",
  3. "$or": [{"qty": {"$lt": 30}}, {"item": {"$regex": "^p"}}]})
  1. findPublisher = collection.find(
  2. and(eq("status", "A"),
  3. or(lt("qty", 30), regex("item", "^p")))
  4. );
  1. var builder = Builders<BsonDocument>.Filter;
  2. var filter = builder.And(
  3. builder.Eq("status", "A"),
  4. builder.Or(builder.Lt("qty", 30), builder.Regex("item", new BsonRegularExpression("^p"))));
  5. var result = collection.Find(filter).ToList();
  1. $cursor = $db->coll("inventory")->find(
  2. {
  3. status => "A",
  4. '$or' => [ { qty => { '$lt' => 30 } }, { item => { '$regex' => "^p" } } ]
  5. }
  6. );
  1. client[:inventory].find(status: 'A',
  2. '$or' => [{ qty: { '$lt' => 30 } },
  3. { item: { '$regex' => BSON::Regexp::Raw.new('^p') } }
  4. ])
  1. findObservable = collection.find(and(
  2. equal("status", "A"),
  3. or(lt("qty", 30), regex("item", "^p")))
  4. )
  1. cursor, err := coll.Find(
  2. context.Background(),
  3. bson.D{
  4. {"status", "A"},
  5. {"$or", bson.A{
  6. bson.D{{"qty", bson.D{{"$lt", 30}}}},
  7. bson.D{{"item", primitive.Regex{Pattern: "^p", Options: ""}}},
  8. }},
  9. })

The operation corresponds to the following SQL statement:

  1. SELECT * FROM inventory WHERE status = "A" AND ( qty < 30 OR item LIKE "p%")

Note

MongoDB supports regular expressions $regex queries toperform string pattern matches.

Additional Query Tutorials

For additional query examples, see:

Behavior

Cursor

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

The db.collection.find() methodreturns a cursor to the matchingdocuments.

The MongoDB Compass Find operation opens acursor to the matchingdocuments of the collection based on the find query.

For more information on sampling in MongoDB Compass, see theCompass FAQ.

The pymongo.collection.Collection.find() methodreturns a cursor to thematching documents. See the PyMongo documentation foriterating over a cursor.

The com.mongodb.client.MongoCollection.find method returns aninstance of the com.mongodb.client.FindIterable interface.

The Collection.find() methodreturns a cursor.

The MongoDB\Collection::find()method returns a cursor tothe matching documents. See the MongoDB PHP Librarydocumentation foriterating over a cursor.

com.mongodb.reactivestreams.client.MongoCollection.find)returns an instance of the com.mongodb.reactivestreams.client.FindPublisherinterface.

The MongoCollection.Find()method returns a cursor tothe matching documents. See the MongoDB C# driverdocumentation foriterating over a cursor.

The MongoDB::Collection::find()method returns a cursor tothe matching documents. See the MongoDB Perl driverdocumentation foriterating over a cursor.

The Mongo::Collection#find()method returns a CollectionView,which is an Enumerable. A Cursor iscreated when the View is enumerated; for example, by calling#to_a() or #each(). You can also get an Enumerator by calling#to_enum() on the View. See the Ruby driver API documentationfor iterating over a cursor.

The collection.find()(implicite:org.mongodb.scala.bson.DefaultHelper.DefaultsTo[C,TResult],implicitct:scala.reflect.ClassTag[C]):org.mongodb.scala.FindObservable[C])method returns the find Observable.

The Collection.Findfunction returns a Cursor to thematching documents. See the Cursordocumentation for more information.

Read Isolation

New in version 3.2.

For reads to replica sets and replica setshards, read concern allows clients to choose alevel of isolation for their reads. For more information, seeRead Concern.

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

Additional Methods

The following methods can also read documents from a collection:

Note

The db.collection.findOne() method also performs a readoperation to return a single document. Internally, thedb.collection.findOne() method is thedb.collection.find() method with a limit of 1.

Additional Options

In addition to filter, MongoDB Compass also allows thefollowing options to be passed to the query bar:

ProjectSpecify which fields to return in the resulting data.
SortSpecify the sort order of the returned documents.
SkipSpecify the first n-number of document to skip before returning the result set.
LimitSpecify the maximum number of documents to return.

Additional Methods

The following methods can also read documents from a collection:

Note

The pymongo.collection.Collection.find_one()method also performs a read operation to return a singledocument. Internally, thepymongo.collection.Collection.find_one() method isthe pymongo.collection.Collection.find() methodwith a limit of 1.

Additional Methods

The following methods can also read documents from a collection:

Additional Methods

The following methods can also read documents from a collection:

Note

The Collection.findOne()method also performs a read operation to return a singledocument. Internally, theCollection.findOne()method is theCollection.find() methodwith a limit of 1.

Additional Methods

The following methods can also read documents from a collection:

Note

The MongoDB\Collection::findOne()method also performs a read operation to return a singledocument. Internally, theMongoDB\Collection::findOne()method is theMongoDB\Collection::find()method with a limit of 1.

Additional Methods

The following methods can also read documents from a collection:

Additional Methods

The following methods can also read documents from a collection:

Note

The MongoCollection.FindOne()method also performs a read operation to return a singledocument. Internally, theMongoCollection.FindOne()method is theMongoCollection.Find()method with a limit of 1.

Additional Methods

The following methods can also read documents from a collection:

Note

The MongoDB::Collection::find_one()method also performs a read operation to return a singledocument. Internally, theMongoDB::Collection::find_one()method is theMongoDB::Collection::find()method with a limit of 1.

Additional Methods

The following methods can also read documents from a collection:

Additional Methods

The following methods can also read documents from a collection:

  • In aggregation pipeline, the$match pipeline stage provides access to MongoDBqueries. See the MongoDB Scala driver’s aggregate method(implicite:org.mongodb.scala.bson.DefaultHelper.DefaultsTo[C,TResult],implicitct:scala.reflect.ClassTag[C]):org.mongodb.scala.AggregateObservable[C]).

Additional Methods

The following methods can also read documents from a collection: