Friday, 7 April 2023

MongoDB Operators: A Beginner's Guide


MongoDB is a popular NoSQL database that stores data in JSON-like documents with dynamic schema. In MongoDB, operators are used to perform various operations on data, including querying, updating, and deleting documents. Let's explore some of the most commonly used MongoDB operators.




Comparison Operators

Comparison operators are used to compare two values and return a boolean value (true or false) based on the comparison. Common comparison operators in MongoDB include:

  • $eq (equal to)
  • $ne (not equal to)
  • $gt (greater than)
  • $lt (less than)
  • $gte (greater than or equal to)
  • $lte (less than or equal to)

Examples:

// Find documents where the age field is equal to 30 db.users.find({ age: { $eq: 30 } }) // Find documents where the salary field is greater than or equal to 10000 db.users.find({ salary: { $gte: 10000 } }) // Find documents where the status field is not equal to "inactive" db.users.find({ status: { $ne: "inactive" } }) // Find documents where the created_at field is less than a specific date db.users.find({ created_at: { $lt: new Date("2022-01-01") } }) // Find documents where the grade field is greater than or equal to 70 and less than or equal to 90 db.students.find({ grade: { $gte: 70, $lte: 90 } })

Logical Operators

Logical operators are used to combine multiple conditions in a query. Common logical operators in MongoDB include:

  • $and
  • $or
  • $not

Examples:

// Find documents where the age field is greater than or equal to 30 and the status field is "active" db.users.find({ $and: [{ age: { $gte: 30 } }, { status: "active" }] }) // Find documents where the role field is "admin" or the status field is "suspended" db.users.find({ $or: [{ role: "admin" }, { status: "suspended" }] }) // Find documents where the age field is less than 30 or the salary field is greater than or equal to 10000 db.users.find({ $or: [{ age: { $lt: 30 } }, { salary: { $gte: 10000 } }] }) // Find documents where the status field is not "active" db.users.find({ status: { $not: { $eq: "active" } } }) // Find documents where the first name field does not contain "John" and the last name field does not contain "Doe" db.users.find({ $and: [{ first_name: { $not: /John/ } }, { last_name: { $not: /Doe/ } }] })



Array Operators

Array operators are used to work with arrays in MongoDB. Common array operators include:

  • $elemMatch (matches documents that contain an array element that matches all the specified criteria)
  • $all (matches documents that contain an array with all the specified elements)
  • $size (matches documents that contain an array with a specific number of elements)

Examples:

// Find documents where the tags field contains the "mongodb" element db.posts.find({ tags: "mongodb" })







No comments:

Post a Comment