MongoDB Document Deletion and Query Operations
Deleting Documents in MongoDB
The remove() method deletes documents from a collection.
db.collection.remove(
<filter>,
{
justOne: <boolean>,
writeConcern: <document>
}
)
- filter: Specifies deletion criteria using a query document.
- justOne: When set to
false(default), removes all matching documents. Set totrueor1to delete only the first matching document. - writeConcern: Optional parameter for error handling.
Example: Delete the first document where the name field equals "MongoDB Guide".
db.articles.remove({'name':'MongoDB Guide'}, true)
Querying Documents
Use find() to retrieve documents.
db.collection.find(filter, projection)
- filter: Query conditions.
- projection: Specifies feilds to return (optional).
For formatted output:
db.collection.find().pretty()
Comparison Operators
| Operator | MongoDB Syntax | Example | SQL Equivalent |
|---|---|---|---|
| Equal | {<field>:<value>} |
db.col.find({"author":"Guide"}).pretty() |
WHERE author = 'Guide' |
| Less Than | {<field>:{$lt:<value>}} |
db.col.find({"views":{$lt:100}}).pretty() |
WHERE views < 100 |
| Less Than or Equal | {<field>:{$lte:<value>}} |
db.col.find({"views":{$lte:100}}).pretty() |
WHERE views <= 100 |
| Greater Than | {<field>:{$gt:<value>}} |
db.col.find({"views":{$gt:100}}).pretty() |
WHERE views > 100 |
| Greater Than or Equal | {<field>:{$gte:<value>}} |
db.col.find({"views":{$gte:100}}).pretty() |
WHERE views >= 100 |
| Not Equal | {<field>:{$ne:<value>}} |
db.col.find({"views":{$ne:100}}).pretty() |
WHERE views != 100 |
Multiple Conditions
Combine conditions with commas for logical AND.
db.col.find({field1:value1, field2:value2}).pretty()
OR Conditions
Use the $or operator.
db.col.find(
{
$or: [
{field1: value1}, {field2:value2}
]
}
).pretty()
Combining AND and OR
Mix conditions for complex queries.
db.col.find({"views": {$gt:50}, $or: [{"author": "Guide"},{"name": "MongoDB Guide"}]}).pretty()