Sling Academy
Home/MongoDB/Using $in and $nin operators in MongoDB (with examples)

Using $in and $nin operators in MongoDB (with examples)

Last updated: February 03, 2024

Introduction

MongoDB, a leading NoSQL database, provides a flexible schema for storing and querying data. Understanding its query operators is crucial for effective data manipulation. Among these, the $in and $nin operators are highly useful for filtering documents based on the presence or absence of values in an array or a field. This tutorial will explore these operators with practical examples to help you harness their full potential.

The $in Operator

The $in operator selects the documents where the value of a field equals any value in the specified array. This operator is particularly useful when you need to query documents based on multiple potential values for a field.

Example 1: Basic Usage of $in

Consider a collection products with several documents. To find products within a specified category list, you’d use the $in operator as follows:

db.products.find({ category: { $in: ['electronics', 'books'] } })

This query will return all products categorized as either ‘electronics’ or ‘books’.

Example 2: Combining $in with Other Operators

You can also combine the $in operator with other MongoDB query operators for more complex queries. For example, to find products within a specific category and price range, you could write:

db.products.find({
    category: { $in: ['electronics', 'books'] },
    price: { $gte: 10, $lte: 100 }
})

This query selects products within the ‘electronics’ and ‘books’ categories that are priced between $10 and $100.

The $nin Operator

The $nin operator is the opposite of $in. It selects the documents where the value of a field does not equal any value in a specified array. This operator is useful for excluding certain values from your results.

Example 3: Basic Usage of $nin

Using the same products collection, if you want to find products outside the ‘electronics’ and ‘books’ categories, you’d use:

db.products.find({ category: { $nin: ['electronics', 'books'] } })

This will return all products not in the ‘electronics’ or ‘books’ categories.

Advanced Usage of $in and $nin

Both $in and $nin can be used for more advanced querying, such as working with arrays or embedded documents.

Example 4: Using $in with Arrays

If you have documents with an array field and you need to find documents where at least one array element meets a condition, you can use $in as follows:

db.users.find({ 'hobbies': { $in: ['reading', 'painting'] } })

This query finds users with ‘reading’ or ‘painting’ as one of their hobbies.

Example 5: Using $nin with Embedded Documents

For a collection of documents where each document contains an embedded document, you can use $nin to exclude documents based on criteria in the embedded documents:

db.orders.find({ 'shipping.address.city': { $nin: ['New York', 'Los Angeles'] } })

This finds orders that are not being shipped to ‘New York’ or ‘Los Angeles’.

To comprehend the nuances of working with $in and $nin, experimenting with them in the context of your database is invaluable. Considering various data shapes and application needs will help you choose the right operator for your queries.

Conclusion

Understanding and utilizing the $in and $nin operators in MongoDB can significantly enhance your data querying capabilities. By selecting or excluding documents based on field values, you can fine-tune your queries for precise data retrieval.

Next Article: Using $and & $or operators in MongoDB (with examples)

Previous Article: Using $lt and $lte operators in MongoDB (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)