Sling Academy
Home/MongoDB/MongoDB: Using $eq and $ne operators to match values (with examples)

MongoDB: Using $eq and $ne operators to match values (with examples)

Last updated: February 02, 2024

Introduction

MongoDB, as a leading NoSQL database, provides flexible query capabilities that allow developers to manipulate and retrieve data efficiently. Two of the primary operators used in querying MongoDB collections are $eq (equal to) and $ne (not equal to). This tutorial covers how to use the $eq and $ne operators with detailed examples, catering to both beginners and advanced users of MongoDB.

Getting Started with $eq and $ne

The $eq operator is used to match documents where the value of a field equals the specified value. Conversely, the $ne operator matches all documents where the field value is not equal to the specified value. Let’s see how they work.

Basic Usage of $eq

To start with an example, let’s assume you have a collection called users and you want to retrieve all users where the age field is exactly 25.

db.users.find({ age: { $eq: 25 } })

This query returns all documents from the users collection where the age is exactly 25.

Output:

[
  { "_id": ObjectId("..."), "name": "Jane Doe", "age": 25 },
  { "_id": ObjectId("..."), "name": "John Doe", "age": 25 }
]

Basic Usage of $ne

On the other hand, if you want to find users whose age is not 25, you would use $ne:

db.users.find({ age: { $ne: 25 } })

This query returns all user documents where the age is not 25.

Output:

[
  { "_id": ObjectId("..."), "name": "Alice Smith", "age": 30 },
  // Add more objects as needed
]

Advanced Querying with $eq and $ne

Now let’s dive deeper into some more complex scenarios where $eq and $ne can be particularly useful.

Using $eq with Embedded Documents

If your collection includes embedded documents, you can still use $eq to match exact values within these sub-documents. For example, let’s assume users have an address embedded document:

db.users.find({ "address.city": { $eq: "New York" } })

This query returns users whose address sub-document has a city field equal to “New York”.

Output:

[
  {
    "_id": ObjectId("..."),
    "name": "Kevin Lee",
    "address": {
      "city": "New York",
      "street": "123 Maple Drive"
    }
  },
  // Add more objects as needed
]

Using $ne with Arrays

If your documents include an array field, $ne can exclude documents based on the absence of a value in an array. Here’s an example of excluding any user who lacks a particular skill:

db.users.find({ skills: { $ne: "Python" } })

This will match documents where the skills array doesn’t contain “Python”.

Output:

[
  {
    "_id": ObjectId("..."),
    "name": "Roberta Flack",
    "skills": ["JavaScript", "C#"]
  },
  // Add more objects as needed
]

Utilizing $eq and $ne in Aggregation

The true power of $eq and $ne shines when using MongoDB’s aggregation framework. With aggregation, you can perform complex filtering and transformations of your data.

Aggregating with $eq

In an aggregation pipeline, $eq is often used within a $match stage to filter documents. An example would be finding all users of a certain age and then grouping by gender:

db.users.aggregate([
  { $match: { age: { $eq: 25 } } },
  { $group: { _id: "$gender", count: { $sum: 1 } } }
])

This aggregation will first filter all users who are 25 years old and then group the remaining documents by gender, counting how many there are of each.

Output:

[
  { "_id": "female", "count": 12 },
  { "_id": "male", "count": 10 }
]

Aggregating with $ne

Similarly, if you wanted to exclude a certain age group in an aggregation, you’d use $ne within a $match operator:

db.users.aggregate([
  { $match: { age: { $ne: 25 } } },
  { $group: { _id: "$gender", count: { $sum: 1 } } }
])

This pipeline will exclude all users who are 25 and then group the remaining users by gender.

Output:

[
  { "_id": "female", "count": 8 },
  { "_id": "male", "count": 9 }
]

In aggregation pipelines, $eq can also be part of expressions in $project and other stages to conditionally modify fields or filter certain values.

Conclusion

In this tutorial, you have learned how the $eq and $ne operators in MongoDB can be an essential part of querying collections. When dealing with equality checks, within embedded documents, arrays, or complex aggregations, $eq and $ne remain versatile tools. They help in crafting precise queries and are fundamental to any MongoDB user’s skill set.

Next Article: MongoDB: Using $gt and $gte operators (with examples)

Previous Article: MongoDB: Excluding sensitive fields from query results (with examples)

Series: MongoDB Tutorials

MongoDB

You May Also Like

  • MongoDB: How to combine data from 2 collections into one
  • Hashed Indexes in MongoDB: A Practical Guide
  • Partitioning and Sharding in MongoDB: A Practical Guide (with Examples)
  • Geospatial Indexes in MongoDB: How to Speed Up Geospatial Queries
  • Understanding Partial Indexes in MongoDB
  • Exploring Sparse Indexes in MongoDB (with Examples)
  • Using Wildcard Indexes in MongoDB: An In-Depth Guide
  • Matching binary values in MongoDB: A practical guide (with examples)
  • Understanding $slice operator in MongoDB (with examples)
  • Caching in MongoDB: A practical guide (with examples)
  • CannotReuseObject Error: Attempted illegal reuse of a Mongo object in the same process space
  • How to perform cascade deletion in MongoDB (with examples)
  • MongoDB: Using $not and $nor operators to negate a query
  • MongoDB: Find SUM/MIN/MAX/AVG of each group in a collection
  • References (Manual Linking) in MongoDB: A Developer’s Guide (with Examples)
  • MongoDB: How to see all fields in a collection (with examples)
  • Type checking in MongoDB: A practical guide (with examples)
  • How to query an array of subdocuments in MongoDB (with examples)
  • MongoDB: How to compare 2 documents (with examples)