MongoDB methods, filters and operators explained

MongoDB offers a rich set of methods, filters, and operators that provide the flexibility to perform a wide range of operations on your data. Understanding these tools is crucial for effective data manipulation and querying in MongoDB.

MongoDB Methods

Methods in MongoDB are functions that execute specific operations, like inserting, updating, deleting, or reading data. Here are some commonly used methods:

CRUD Operations

  • insertOne(): Inserts a single document into a collection.
  • insertMany(): Inserts multiple documents into a collection.
  • find(): Searches for documents in a collection.
  • updateOne(): Updates a single document.
  • updateMany(): Updates multiple documents.
  • deleteOne(): Deletes a single document.
  • deleteMany(): Deletes multiple documents.

Aggregation and Indexing

  • aggregate(): Performs data aggregation based on specified pipeline stages.
  • createIndex(): Creates an index on a specific field or fields.

Filters

Filters are query conditions used to search for and manipulate documents. Filters in MongoDB use JSON-like syntax and can be used in various methods like find(), updateOne(), etc.

Basic Filter

To find all students aged 21:

db.collection('students').find({ age: 21 });

Compound Filters

To find all students aged 21 and named John:

db.collection('students').find({ age: 21, name: "John" });

Operators

MongoDB provides a wide array of operators to use in filters for more complex queries.

Comparison Operators

  • $eq: Matches values that are equal to a specified value.
  • $gt: Matches values that are greater than a specified value.
  • $lt: Matches values that are less than a specified value.

Logical Operators

  • $and: Joins query clauses with a logical AND.
  • $or: Joins query clauses with a logical OR.

Array Operators

  • $in: Matches any of the values specified in an array.
  • $all: Matches all the values specified in an array.

Update Operators

  • $set: Sets the value of a field in a document.
  • $inc: Increments the value of a field by a specified amount.

Example: Using Operators

To find students aged over 21 and update their status:

db.collection('students').updateMany(
{ age: { $gt: 21 } },
{ $set: { status: "overage" } }
);

Summary

MongoDB methods, filters, and operators are the essential components of your MongoDB toolkit. Methods perform specific operations like CRUD, aggregation, and indexing. Filters help you pinpoint the data you’re interested in, and operators offer the syntactical sugar to make your queries more expressive and powerful.

,