MongoDB Query Documents
MongoDB query documents use thefind()、findOne()method.
The find() method displays all documents in an unstructured format.
Syntax
The syntax format for MongoDB querying data is as follows:
db.collection.find(query, projection)
- query: The query criteria used to find documents. Defaults to
{}, which matches all documents. - projection(Optional): Specifies the fields to include or exclude in the returned results.
Find all documents:
Example
Find documents by criteria:
Example
Find documents by criteria and return only the specified fields:
Example
{ age: { $gt: 25 } },
{ name: 1, age: 1, _id: 0 }
);
If you need to read the data in a readable format, you can use the pretty() method. The syntax format is as follows:
>db.col.find().pretty()
The pretty() method displays all documents in a formatted way.
Example
{
"_id" : ObjectId("56063f17ade2f21f36b03133"),
"title" : "MongoDB Tutorial",
"description" : "MongoDB is a NoSQL database",
"by" : "Example Tutorial",
"url" : "http://www.example.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
2、findOne()
The findOne() method is used to find a single document in a collection. If multiple matching documents are found, it returns only the first one.
Syntax:
db.collection.findOne(query, projection)
- query: The query criteria used to find documents. Defaults to
{}, which matches all documents. - projection(Optional): Specifies the fields to include or exclude in the returned results.
Find a single document:
db.myCollection.findOne({ name: "Alice" });Find a single document and return only the specified fields:
db.myCollection.findOne(
{ name: "Alice" },
{ name: 1, age: 1, _id: 0 }
);
Advanced Query Methods
1. Using Comparison Operators
MongoDB supports various comparison operators, such as$gt、$lt、$gte、$lte、$eq、$neetc.
Find documents where age is greater than 25:
db.myCollection.find({ age: { $gt: 25 } });
2. Using Logical Operators
MongoDB supports various logical operators, such as$and、$or、$not、$noretc.
Find documents where age is greater than 25 and city is "New York":
Example
$and: [
{ age: { $gt: 25 } },
{ city: "New York" }
]
});
3. Using Regular Expressions
Regular expressions can be used for pattern matching queries.
Find documents where the name starts with "A":
db.myCollection.find({ name: /^A/ });
4. Projection
Projection is used to control which fields are returned in the query results. You can use either inclusion mode or exclusion mode.
Return only the name and age fields:
Example
{ age: { $gt: 25 } },
{ name: 1, age: 1, _id: 0 }
);
5. Sorting
You can sort the query results.
Sort by age in descending order:
db.myCollection.find().sort({ age: -1 });
6. Limit and Skip
You can limit the query results and skip a specified number of documents.
Return the first 10 documents:
db.myCollection.find().limit(10);
Skip the first 5 documents and return the next 10 documents:
db.myCollection.find().skip(5).limit(10);
Example
Find documents where age is greater than 25 and city is "New York", return only the name and age fields, sort by age in descending order, and return the first 10 documents.
Example
{
$and: [
{ age: { $gt: 25 } },
{ city: "New York" }
]
},
{ name: 1, age: 1, _id: 0 }
).sort({ age: -1 }).limit(10);
MongoDB vs RDBMS WHERE Clause Comparison
If you are familiar with conventional SQL data, you can better understand MongoDB's conditional query statements through the following table:
| Operation | Format | Example | Similar statement in RDBMS |
|---|---|---|---|
| Equals | {<key>:<value>} |
db.col.find({"by":"Example"}).pretty() |
where by = 'Example' |
| Less than | {<key>:{$lt:<value>}} |
db.col.find({"likes":{$lt:50}}).pretty() |
where likes < 50 |
| Less than or equal to | {<key>:{$lte:<value>}} |
db.col.find({"likes":{$lte:50}}).pretty() |
where likes <= 50 |
| Greater than | {<key>:{$gt:<value>}} |
db.col.find({"likes":{$gt:50}}).pretty() |
where likes > 50 |
| Greater than or equal to | {<key>:{$gte:<value>}} |
db.col.find({"likes":{$gte:50}}).pretty() |
where likes >= 50 |
| Not equal to | {<key>:{$ne:<value>}} |
db.col.find({"likes":{$ne:50}}).pretty() |
where likes != 50 |
MongoDB AND Conditions
MongoDB's find() method can accept multiple keys, with each key separated by a comma, which is the AND condition in conventional SQL.
The syntax format is as follows:
>db.col.find({key1:value1, key2:value2}).pretty()
Example
The following example uses thebyandtitlekey to queryExample TutorialMediumMongoDB Tutorialdata
> db.col.find({"by":"Example", "title":"MongoDB 教程"}).pretty()
{
"_id" : ObjectId("56063f17ade2f21f36b03133"),
"title" : "MongoDB 教程",
"description" : "MongoDB 是一个 Nosql 数据库",
"by" : "Example",
"url" : "http://www.example.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
The above example is similar to the WHERE statement:WHERE by='Example Tutorial' AND title='MongoDB Tutorial'
MongoDB OR Conditions
MongoDB OR condition statements use the keyword$or, the syntax format is as follows:
>db.col.find(
{
$or: [
{key1: value1}, {key2:value2}
]
}
).pretty()
Example
In the following example, we demonstrate querying the keybywith the valueExample Tutorialor the keytitlewith the valueMongoDB Tutorialdocuments.
>db.col.find({$or:[{"by":"Example"},{"title": "MongoDB 教程"}]}).pretty()
{
"_id" : ObjectId("56063f17ade2f21f36b03133"),
"title" : "MongoDB 教程",
"description" : "MongoDB 是一个 Nosql 数据库",
"by" : "Example",
"url" : "http://www.example.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
>
Combining AND and OR
The following example demonstrates the combined use of AND and OR, similar to the conventional SQL statement:'where likes>50 AND (by = 'Example Tutorial' OR title = 'MongoDB Tutorial')'
>db.col.find({"likes": {$gt:50}, $or: [{"by": "Example"},{"title": "MongoDB 教程"}]}).pretty()
{
"_id" : ObjectId("56063f17ade2f21f36b03133"),
"title" : "MongoDB 教程",
"description" : "MongoDB 是一个 Nosql 数据库",
"by" : "Example",
"url" : "http://www.example.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
Other Extensions