- Query Documents
- Select All Documents in a Collection
- Specify Equality Condition
- Specify Conditions Using Query Operators
- Specify AND Conditions
- Specify OR Conditions
- Additional Query Tutorials
- Behavior
- Additional Methods
- Additional Options
- Additional Methods
- Additional Methods
- Additional Methods
- Additional Methods
- Additional Methods
- Additional Methods
- Additional Methods
- Additional Methods
- Additional Methods
- Additional Methods
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 inventory
collection, 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 inventory
collection. 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 inventory
collection. 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 inventory
collection. 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 inventory
collection. 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
- db.inventory.insertMany([
- { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
- { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
- { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
- { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
- { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
- ]);
You can run the operation in the web shell below:
- [
- { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
- { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
- { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
- { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
- { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
- ]
For instructions on inserting documents in MongoDB Compass, seeInsert Documents.
- db.inventory.insert_many([
- {"item": "journal",
- "qty": 25,
- "size": {"h": 14, "w": 21, "uom": "cm"},
- "status": "A"},
- {"item": "notebook",
- "qty": 50,
- "size": {"h": 8.5, "w": 11, "uom": "in"},
- "status": "A"},
- {"item": "paper",
- "qty": 100,
- "size": {"h": 8.5, "w": 11, "uom": "in"},
- "status": "D"},
- {"item": "planner",
- "qty": 75, "size": {"h": 22.85, "w": 30, "uom": "cm"},
- "status": "D"},
- {"item": "postcard",
- "qty": 45,
- "size": {"h": 10, "w": 15.25, "uom": "cm"},
- "status": "A"}])
- collection.insertMany(asList(
- Document.parse("{ item: 'journal', qty: 25, size: { h: 14, w: 21, uom: 'cm' }, status: 'A' }"),
- Document.parse("{ item: 'notebook', qty: 50, size: { h: 8.5, w: 11, uom: 'in' }, status: 'A' }"),
- Document.parse("{ item: 'paper', qty: 100, size: { h: 8.5, w: 11, uom: 'in' }, status: 'D' }"),
- Document.parse("{ item: 'planner', qty: 75, size: { h: 22.85, w: 30, uom: 'cm' }, status: 'D' }"),
- Document.parse("{ item: 'postcard', qty: 45, size: { h: 10, w: 15.25, uom: 'cm' }, status: 'A' }")
- ));
- await db.collection('inventory').insertMany([
- {
- item: 'journal',
- qty: 25,
- size: { h: 14, w: 21, uom: 'cm' },
- status: 'A'
- },
- {
- item: 'notebook',
- qty: 50,
- size: { h: 8.5, w: 11, uom: 'in' },
- status: 'A'
- },
- {
- item: 'paper',
- qty: 100,
- size: { h: 8.5, w: 11, uom: 'in' },
- status: 'D'
- },
- {
- item: 'planner',
- qty: 75,
- size: { h: 22.85, w: 30, uom: 'cm' },
- status: 'D'
- },
- {
- item: 'postcard',
- qty: 45,
- size: { h: 10, w: 15.25, uom: 'cm' },
- status: 'A'
- }
- ]);
- $insertManyResult = $db->inventory->insertMany([
- [
- 'item' => 'journal',
- 'qty' => 25,
- 'size' => ['h' => 14, 'w' => 21, 'uom' => 'cm'],
- 'status' => 'A',
- ],
- [
- 'item' => 'notebook',
- 'qty' => 50,
- 'size' => ['h' => 8.5, 'w' => 11, 'uom' => 'in'],
- 'status' => 'A',
- ],
- [
- 'item' => 'paper',
- 'qty' => 100,
- 'size' => ['h' => 8.5, 'w' => 11, 'uom' => 'in'],
- 'status' => 'D',
- ],
- [
- 'item' => 'planner',
- 'qty' => 75,
- 'size' => ['h' => 22.85, 'w' => 30, 'uom' => 'cm'],
- 'status' => 'D',
- ],
- [
- 'item' => 'postcard',
- 'qty' => 45,
- 'size' => ['h' => 10, 'w' => 15.25, 'uom' => 'cm'],
- 'status' => 'A',
- ],
- ]);
- await db.inventory.insert_many([
- {"item": "journal",
- "qty": 25,
- "size": {"h": 14, "w": 21, "uom": "cm"},
- "status": "A"},
- {"item": "notebook",
- "qty": 50,
- "size": {"h": 8.5, "w": 11, "uom": "in"},
- "status": "A"},
- {"item": "paper",
- "qty": 100,
- "size": {"h": 8.5, "w": 11, "uom": "in"},
- "status": "D"},
- {"item": "planner",
- "qty": 75, "size": {"h": 22.85, "w": 30, "uom": "cm"},
- "status": "D"},
- {"item": "postcard",
- "qty": 45,
- "size": {"h": 10, "w": 15.25, "uom": "cm"},
- "status": "A"}])
- Publisher<Success> insertManyPublisher = collection.insertMany(asList(
- Document.parse("{ item: 'journal', qty: 25, size: { h: 14, w: 21, uom: 'cm' }, status: 'A' }"),
- Document.parse("{ item: 'notebook', qty: 50, size: { h: 8.5, w: 11, uom: 'in' }, status: 'A' }"),
- Document.parse("{ item: 'paper', qty: 100, size: { h: 8.5, w: 11, uom: 'in' }, status: 'D' }"),
- Document.parse("{ item: 'planner', qty: 75, size: { h: 22.85, w: 30, uom: 'cm' }, status: 'D' }"),
- Document.parse("{ item: 'postcard', qty: 45, size: { h: 10, w: 15.25, uom: 'cm' }, status: 'A' }")
- ));
- var documents = new BsonDocument[]
- {
- new BsonDocument
- {
- { "item", "journal" },
- { "qty", 25 },
- { "size", new BsonDocument { { "h", 14 }, { "w", 21 }, { "uom", "cm"} } },
- { "status", "A" }
- },
- new BsonDocument
- {
- { "item", "notebook" },
- { "qty", 50 },
- { "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in"} } },
- { "status", "A" }
- },
- new BsonDocument
- {
- { "item", "paper" },
- { "qty", 100 },
- { "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in"} } },
- { "status", "D" }
- },
- new BsonDocument
- {
- { "item", "planner" },
- { "qty", 75 },
- { "size", new BsonDocument { { "h", 22.85 }, { "w", 30 }, { "uom", "cm"} } },
- { "status", "D" }
- },
- new BsonDocument
- {
- { "item", "postcard" },
- { "qty", 45 },
- { "size", new BsonDocument { { "h", 10 }, { "w", 15.25 }, { "uom", "cm"} } },
- { "status", "A" }
- },
- };
- collection.InsertMany(documents);
- $db->coll("inventory")->insert_many(
- [
- {
- item => "journal",
- qty => 25,
- size => { h => 14, w => 21, uom => "cm" },
- status => "A"
- },
- {
- item => "notebook",
- qty => 50,
- size => { h => 8.5, w => 11, uom => "in" },
- status => "A"
- },
- {
- item => "paper",
- qty => 100,
- size => { h => 8.5, w => 11, uom => "in" },
- status => "D"
- },
- {
- item => "planner",
- qty => 75,
- size => { h => 22.85, w => 30, uom => "cm" },
- status => "D"
- },
- {
- item => "postcard",
- qty => 45,
- size => { h => 10, w => 15.25, uom => "cm" },
- status => "A"
- }
- ]
- );
- client[:inventory].insert_many([{ item: 'journal',
- qty: 25,
- size: { h: 14, w: 21, uom: 'cm' },
- status: 'A' },
- { item: 'notebook',
- qty: 50,
- size: { h: 8.5, w: 11, uom: 'in' },
- status: 'A' },
- { item: 'paper',
- qty: 100,
- size: { h: 8.5, w: 11, uom: 'in' },
- status: 'D' },
- { item: 'planner',
- qty: 75,
- size: { h: 22.85, w: 30, uom: 'cm' },
- status: 'D' },
- { item: 'postcard',
- qty: 45,
- size: { h: 10, w: 15.25, uom: 'cm' },
- status: 'A' }
- ])
- collection.insertMany(Seq(
- Document("""{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" }"""),
- Document("""{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" }"""),
- Document("""{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" }"""),
- Document("""{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" }"""),
- Document("""{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }""")
- )).execute()
- docs := []interface{}{
- bson.D{
- {"item", "journal"},
- {"qty", 25},
- {"size", bson.D{
- {"h", 14},
- {"w", 21},
- {"uom", "cm"},
- }},
- {"status", "A"},
- },
- bson.D{
- {"item", "notebook"},
- {"qty", 50},
- {"size", bson.D{
- {"h", 8.5},
- {"w", 11},
- {"uom", "in"},
- }},
- {"status", "A"},
- },
- bson.D{
- {"item", "paper"},
- {"qty", 100},
- {"size", bson.D{
- {"h", 8.5},
- {"w", 11},
- {"uom", "in"},
- }},
- {"status", "D"},
- },
- bson.D{
- {"item", "planner"},
- {"qty", 75},
- {"size", bson.D{
- {"h", 22.85},
- {"w", 30},
- {"uom", "cm"},
- }},
- {"status", "D"},
- },
- bson.D{
- {"item", "postcard"},
- {"qty", 45},
- {"size", bson.D{
- {"h", 10},
- {"w", 15.25},
- {"uom", "cm"},
- }},
- {"status", "A"},
- },
- }
- 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
- db.inventory.find( {} )
- cursor = db.inventory.find({})
- FindIterable<Document> findIterable = collection.find(new Document());
- const cursor = db.collection('inventory').find({});
- $cursor = $db->inventory->find([]);
- cursor = db.inventory.find({})
- FindPublisher<Document> findPublisher = collection.find(new Document());
- var filter = Builders<BsonDocument>.Filter.Empty;
- var result = collection.Find(filter).ToList();
- $cursor = $db->coll("inventory")->find( {} );
- client[:inventory].find({})
- var findObservable = collection.find(Document())
- cursor, err := coll.Find(
- context.Background(),
- bson.D{},
- )
This operation corresponds to the following SQL statement:
- 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:
- { <field1>: <value1>, ... }
To specify equality conditions, use <field>:<value>
expressions in thequery filter document:
- { <field1>: <value1>, ... }
To specify equality conditions, use <field>:<value>
expressions in thequery filter document:
- { <field1>: <value1>, ... }
To specify equality conditions, use thecom.mongodb.client.model.Filters.eq_
method to create thequery filter document:
- and(eq( <field1>, <value1>), eq( <field2>, <value2>) ...)
To specify equality conditions, use <field>:<value>
expressions in thequery filter document:
- { <field1>: <value1>, ... }
To specify equality conditions, use <field> => <value>
expressions in thequery filter document:
- [ <field1> => <value1>, ... ]
To specify equality conditions, use <field>:<value>
expressions in thequery filter document:
- { <field1>: <value1>, ... }
To specify equality conditions, use thecom.mongodb.client.model.Filters.eq method to create thequery filter document:
- and(eq( <field1>, <value1>), eq( <field2>, <value2>) ...)
To specify equality conditions, construct a filter using theEq method:
- Builders<BsonDocument>.Filter.Eq(<field>, <value>);
To specify equality conditions, use <field> => <value>
expressions in thequery filter document:
- { <field1> => <value1>, ... }
To specify equality conditions, use <field> => <value>
expressions in thequery filter document:
- { <field1> => <value1>, ... }
To specify equality conditions, use thecom.mongodb.client.model.Filters.eq_
method to create thequery filter document:
- 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
- db.inventory.find( { status: "D" } )
Copy the following filter into the Compass query bar and clickFind:
- { status: "D" }
- cursor = db.inventory.find({"status": "D"})
- findIterable = collection.find(eq("status", "D"));
- const cursor = db.collection('inventory').find({ status: 'D' });
- $cursor = $db->inventory->find(['status' => 'D']);
- cursor = db.inventory.find({"status": "D"})
- findPublisher = collection.find(eq("status", "D"));
- var filter = Builders<BsonDocument>.Filter.Eq("status", "D");
- var result = collection.Find(filter).ToList();
- $cursor = $db->coll("inventory")->find( { status => "D" } );
- client[:inventory].find(status: 'D')
- findObservable = collection.find(equal("status", "D"))
- cursor, err := coll.Find(
- context.Background(),
- bson.D{{"status", "D"}},
- )
This operation corresponds to the following SQL statement:
- 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:
- { <field1>: { <operator1>: <value1> }, ... }
A query filter document canuse the query operators to specifyconditions in the following form:
- { <field1>: { <operator1>: <value1> }, ... }
A query filter document canuse the query operators to specifyconditions in the following form:
- { <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:
- and(gte(<field1>, <value1>), lt(<field2>, <value2>), eq(<field3>, <value3>))
A query filter document canuse the query operators to specifyconditions in the following form:
- { <field1>: { <operator1>: <value1> }, ... }
A query filter document canuse the query operators to specifyconditions in the following form:
- [ <field1> => [ <operator1> => <value1> ], ... ]
A query filter document canuse the query operators to specifyconditions in the following form:
- { <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:
- 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:
- var builder = Builders<BsonDocument>.Filter;
- builder.And(builder.Eq(<field1>, <value1>), builder.Lt(<field2>, <value2>));
A query filter document canuse the query operators to specifyconditions in the following form:
- { <field1> => { <operator1> => <value1> }, ... }
A query filter document canuse the query operators to specifyconditions in the following form:
- { <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:
- and(gte(<field1>, <value1>), lt(<field2>, <value2>), equal(<field3>, <value3>))
The following example retrieves all documents from the inventory
collection 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
- db.inventory.find( { status: { $in: [ "A", "D" ] } } )
Copy the following filter into the Compass query bar and clickFind:
- { status: { $in: [ "A", "D" ] } }
- cursor = db.inventory.find({"status": {"$in": ["A", "D"]}})
- findIterable = collection.find(in("status", "A", "D"));
- const cursor = db.collection('inventory').find({
- status: { $in: ['A', 'D'] }
- });
- $cursor = $db->inventory->find(['status' => ['$in' => ['A', 'D']]]);
- cursor = db.inventory.find({"status": {"$in": ["A", "D"]}})
- findPublisher = collection.find(in("status", "A", "D"));
- var filter = Builders<BsonDocument>.Filter.In("status", new[] { "A", "D" });
- var result = collection.Find(filter).ToList();
- $cursor = $db->coll("inventory")->find( { status => { '$in' => [ "A", "D" ] } } );
- client[:inventory].find(status: { '$in' => [ 'A', 'D' ]})
- findObservable = collection.find(in("status", "A", "D"))
- cursor, err := coll.Find(
- context.Background(),
- 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 $or
operator when performing equality checks on the same field.
The operation corresponds to the following SQL statement:
- 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 inventory
collection 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
- db.inventory.find( { status: "A", qty: { $lt: 30 } } )
Copy the following filter into the Compass query bar and clickFind:
- { status: "A", qty: { $lt: 30 } }
- cursor = db.inventory.find({"status": "A", "qty": {"$lt": 30}})
- findIterable = collection.find(and(eq("status", "A"), lt("qty", 30)));
- const cursor = db.collection('inventory').find({
- status: 'A',
- qty: { $lt: 30 }
- });
- $cursor = $db->inventory->find([
- 'status' => 'A',
- 'qty' => ['$lt' => 30],
- ]);
- cursor = db.inventory.find({"status": "A", "qty": {"$lt": 30}})
- findPublisher = collection.find(and(eq("status", "A"), lt("qty", 30)));
- var builder = Builders<BsonDocument>.Filter;
- var filter = builder.And(builder.Eq("status", "A"), builder.Lt("qty", 30));
- var result = collection.Find(filter).ToList();
- $cursor = $db->coll("inventory")->find( { status => "A", qty => { '$lt' => 30 } } );
- client[:inventory].find(status: 'A', qty: { '$lt' => 30 })
- findObservable = collection.find(and(equal("status", "A"), lt("qty", 30)))
- cursor, err := coll.Find(
- context.Background(),
- bson.D{
- {"status", "A"},
- {"qty", bson.D{{"$lt", 30}}},
- })
The operation corresponds to the following SQL statement:
- 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
- db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )
Copy the following filter into the Compass query bar and clickFind:
- { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] }
- cursor = db.inventory.find(
- {"$or": [{"status": "A"}, {"qty": {"$lt": 30}}]})
- findIterable = collection.find(or(eq("status", "A"), lt("qty", 30)));
- const cursor = db.collection('inventory').find({
- $or: [{ status: 'A' }, { qty: { $lt: 30 } }]
- });
- $cursor = $db->inventory->find([
- '$or' => [
- ['status' => 'A'],
- ['qty' => ['$lt' => 30]],
- ],
- ]);
- cursor = db.inventory.find(
- {"$or": [{"status": "A"}, {"qty": {"$lt": 30}}]})
- findPublisher = collection.find(or(eq("status", "A"), lt("qty", 30)));
- var builder = Builders<BsonDocument>.Filter;
- var filter = builder.Or(builder.Eq("status", "A"), builder.Lt("qty", 30));
- var result = collection.Find(filter).ToList();
- $cursor = $db->coll("inventory")->find(
- { '$or' => [ { status => "A" }, { qty => { '$lt' => 30 } } ] }
- );
- client[:inventory].find('$or' => [{ status: 'A' },
- { qty: { '$lt' => 30 } }
- ])
- findObservable = collection.find(or(equal("status", "A"), lt("qty", 30)))
- cursor, err := coll.Find(
- context.Background(),
- bson.D{
- {"$or",
- bson.A{
- bson.D{{"status", "A"}},
- bson.D{{"qty", bson.D{{"$lt", 30}}}},
- }},
- })
The operation corresponds to the following SQL statement:
- 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
- db.inventory.find( {
- status: "A",
- $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]
- } )
Copy the following filter into the Compass query bar and clickFind:
- { status: "A", $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ] }
- cursor = db.inventory.find({
- "status": "A",
- "$or": [{"qty": {"$lt": 30}}, {"item": {"$regex": "^p"}}]})
- findIterable = collection.find(
- and(eq("status", "A"),
- or(lt("qty", 30), regex("item", "^p")))
- );
- const cursor = db.collection('inventory').find({
- status: 'A',
- $or: [{ qty: { $lt: 30 } }, { item: { $regex: '^p' } }]
- });
- $cursor = $db->inventory->find([
- 'status' => 'A',
- '$or' => [
- ['qty' => ['$lt' => 30]],
- // Alternatively: ['item' => new \MongoDB\BSON\Regex('^p')]
- ['item' => ['$regex' => '^p']],
- ],
- ]);
- cursor = db.inventory.find({
- "status": "A",
- "$or": [{"qty": {"$lt": 30}}, {"item": {"$regex": "^p"}}]})
- findPublisher = collection.find(
- and(eq("status", "A"),
- or(lt("qty", 30), regex("item", "^p")))
- );
- var builder = Builders<BsonDocument>.Filter;
- var filter = builder.And(
- builder.Eq("status", "A"),
- builder.Or(builder.Lt("qty", 30), builder.Regex("item", new BsonRegularExpression("^p"))));
- var result = collection.Find(filter).ToList();
- $cursor = $db->coll("inventory")->find(
- {
- status => "A",
- '$or' => [ { qty => { '$lt' => 30 } }, { item => { '$regex' => "^p" } } ]
- }
- );
- client[:inventory].find(status: 'A',
- '$or' => [{ qty: { '$lt' => 30 } },
- { item: { '$regex' => BSON::Regexp::Raw.new('^p') } }
- ])
- findObservable = collection.find(and(
- equal("status", "A"),
- or(lt("qty", 30), regex("item", "^p")))
- )
- cursor, err := coll.Find(
- context.Background(),
- bson.D{
- {"status", "A"},
- {"$or", bson.A{
- bson.D{{"qty", bson.D{{"$lt", 30}}}},
- bson.D{{"item", primitive.Regex{Pattern: "^p", Options: ""}}},
- }},
- })
The operation corresponds to the following SQL statement:
- 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:
- Query on Embedded/Nested Documents
- Query an Array
- Query an Array of Embedded Documents
- Project Fields to Return from Query
- Query for Null or Missing Fields
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:
db.collection.findOne
- In aggregation pipeline, the
$match
pipeline stage provides access to MongoDBqueries.
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:
Project | Specify which fields to return in the resulting data. |
Sort | Specify the sort order of the returned documents. |
Skip | Specify the first n-number of document to skip before returning the result set. |
Limit | Specify the maximum number of documents to return. |
Additional Methods
The following methods can also read documents from a collection:
pymongo.collection.Collection.find_one()
- In aggregation pipeline, the
$match
pipeline stage provides access to MongoDBqueries. See the PyMongo Aggregation Examples.
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:
- In the aggregation pipeline,the
$match
pipeline stage provides access toMongoDB queries. See the Java Synchronous Driver AggregationExamples.
Additional Methods
The following methods can also read documents from a collection:
- Collection.findOne()
- In aggregation pipeline, the
$match
pipeline stage provides access to MongoDBqueries. See the MongoDB Node.js Driver’saggregation tutorial.
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:
MongoDB\Collection::findOne()
- In aggregation pipeline, the
$match
pipeline stage provides access to MongoDBqueries. See the MongoDB PHP Library’saggregation example.
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:
- In aggregation pipeline,the
$match
pipeline stage provides access toMongoDB queries. See com.mongodb.reactivestreams.client.MongoCollection.aggregate)for more information.
Additional Methods
The following methods can also read documents from a collection:
- MongoCollection.FindOne()
- In aggregation pipeline, the
$match
pipeline stage provides access to MongoDBqueries. See the MongoDB C# driver’sLINQ documentation.
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:
- MongoDB::Collection::find_one()
- In aggregation pipeline, the
$match
pipeline stage provides access to MongoDBqueries. See the MongoDB Perl driver’saggregation examples.
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:
- In aggregation pipeline, the
$match
pipeline stage provides access to MongoDBqueries. See the MongoDB Ruby driver’saggregation examples.
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:
- Collection.FindOne
- In aggregation pipeline,the
$match
pipeline stage provides access toMongoDB queries. SeeCollection.Aggregate.