mongodbHow to use the "and" operator in MongoDB?
The and
operator in MongoDB is used to combine two or more expressions and retrieve documents that match all the expressions in the query.
For example, the following query will return documents that have the name
field set to John
and the age
field set to 25
:
db.collection.find({name: "John", age: 25})
The output of the above query will be documents that match both the name
and age
criteria:
{
"_id": ObjectId("5f3d7f3f3f3f3f3f3f3f3f3f"),
"name": "John",
"age": 25
}
The and
operator can also be used to combine multiple expressions in a single query. For example, the following query will return documents that have the name
field set to John
, the age
field set to 25
and the gender
field set to male
:
db.collection.find({name: "John", age: 25, gender: "male"})
The output of the above query will be documents that match all the criteria:
{
"_id": ObjectId("5f3d7f3f3f3f3f3f3f3f3f3f"),
"name": "John",
"age": 25,
"gender": "male"
}
The and
operator can also be used to combine multiple expressions in a single query using the $and
operator. For example, the following query will return documents that have the name
field set to John
and the age
field set to 25
or the gender
field set to male
:
db.collection.find({$and: [{name: "John"}, {$or: [{age: 25}, {gender: "male"}]}]})
The output of the above query will be documents that match either the name
and age
criteria or the name
and gender
criteria:
{
"_id": ObjectId("5f3d7f3f3f3f3f3f3f3f3f3f"),
"name": "John",
"age": 25
},
{
"_id": ObjectId("5f3d7f3f3f3f3f3f3f3f3f3f"),
"name": "John",
"gender": "male"
}
Helpful links
More of Mongodb
- How to check the version of MongoDB?
- How to remove a field from MongoDB?
- How to create a many to many relation in MongoDB?
- How to use transactions in MongoDB?
- How to use regex in MongoDB?
- How to work with JSON data in MongoDB?
- How to perform a health check for MongoDB?
- How to work with time series data in MongoDB?
- How to use watch in MongoDB?
- How to insert new document into MongoDB?
See more codes...