MongoDB Operators
MongoDB provides various query operators that allow you to perform complex queries and filtering operations on your data.
OR Operator ($or
)
$or
)The $or
operator allows you to perform a logical OR operation on an array of query expressions. It returns documents that match at least one of the specified expressions.
db.collectionName.find({
$or: [
{category: "books"},
{category: "electronics"},
{price: {$gt: 50}}
]
})
This query will return documents where the category is either "books" or "electronics", or where the price is greater than 50.
NOR Operator ($nor
)
$nor
)The $nor
operator is the logical complement of the $or
operator. It returns documents that do not match any of the specified expressions.
db.collectionName.find({
$nor: [
{category: "books"},
{category: "electronics"},
{price: {$gt: 50}}
]
})
This query will return documents where the category is neither "books" nor "electronics", and the price is not greater than 50.
NOT Operator ($not
)
$not
)The $not
operator is used to negate the result of a query expression. It returns documents that do not match the specified expression.
db.collectionName.find({
name: {$not: /^A/}
})
This query will return documents where the name field does not start with the letter "A".
Limiting and Skipping Documents
You can limit the number of documents returned by a query using the limit()
method:
db.collectionName.find().limit(5)
This will return only the first 5 documents from the result set.
To skip a specified number of documents, use the skip()
method:
db.collectionName.find().skip(10).limit(5)
This will skip the first 10 documents and return the next 5 documents from the result set.
Last updated
Was this helpful?