Visit complete MongoDB roadmap

← Back to Topics List

$ne

In MongoDB, the $ne operator is used to filter documents where the value of a specified field is not equal to a specified value.

Usage

To use the $ne comparison operator, include it within the query document as:

{
  field: {
    $ne: value;
  }
}
  • field : The field that you want to apply the $ne operator on.
  • value : The value that you want to filter out from the results.

Example

Let’s say you have a collection called products with documents like:

{ _id: 1, name: "Apple", category: "Fruits" }
{ _id: 2, name: "Banana", category: "Fruits" }
{ _id: 3, name: "Carrot", category: "Vegetables" }

If you want to query all documents where the category is not “Fruits”, you would execute:

db.products.find({ category: { $ne: 'Fruits' } });

The result would be:

{ "_id" : 3, "name" : "Carrot", "category" : "Vegetables" }

Additional Notes

  • The $ne operator also works with compound conditions.
  • You can compare values of different types (e.g., a string and a number), but remember that MongoDB uses BSON’s comparison rules for different data types.

And that’s a brief summary of the $ne operator. Use it when you want to filter documents where a specified field’s value is not equal to another specified value. Happy querying!

Community

roadmap.sh is the 6th most starred project on GitHub and is visited by hundreds of thousands of developers every month.

Roadmaps Best Practices Guides Videos Store YouTube

roadmap.sh by Kamran Ahmed

Community created roadmaps, articles, resources and journeys to help you choose your path and grow in your career.

© roadmap.sh · FAQs · Terms · Privacy

ThewNewStack

The leading DevOps resource for Kubernetes, cloud-native computing, and the latest in at-scale development, deployment, and management.