Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

MongoDB Document Deletion and Query Operations

Tech 2

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 to true or 1 to 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()

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.