Sling Academy
Home/MongoDB/MongoDB: Find documents whose array contains a specific value

MongoDB: Find documents whose array contains a specific value

Last updated: February 03, 2024

Introduction

Finding documents in a MongoDB database that contain an array with a specific value is a common task for developers. This tutorial will explore various scenarios, ranging from basic finds to more complex searches, to help you master querying documents based on the contents of an array field.

Let’s start with understanding the basic query for finding documents where an array contains a specific value and gradually move towards more complex queries.

Basic Example

Consider a collection named users with documents resembling the following structure:

{
  "name": "John Doe",
  "interests": ["coding", "hiking", "cooking"]
}

Our goal is to find users who are interested in ‘coding’. Here’s how you can achieve that:

db.users.find({"interests": "coding"})

This query returns all documents where the interests array contains ‘coding’.

Using $in for Multiple Values

What if you want to find users interested in either ‘coding’ or ‘hiking’? You can use the $in operator as follows:

db.users.find({"interests": {"$in": ["coding", "hiking"]}})

This query returns documents where the interests array contains either ‘coding’, ‘hiking’, or both.

Working with Nested Arrays

Let’s take our queries a notch higher. Consider a collection orders, where each document contains nested arrays:

{
  "order_id": 123,
  "products": [
    { "name": "laptop", "quantity": 2 },
    { "name": "phone", "quantity": 1 }
  ]
}

To find orders that include a ‘laptop’, you need to match objects within an array. You can achieve this by using the dot notation and the $elemMatch operator:

db.orders.find({"products": {"$elemMatch": {"name": "laptop"}}})

This query will search through each object in the products array to find at least one object with the name key equal to ‘laptop’.

Matching Multiple Conditions in Nested Arrays

If you want to find documents where the products array includes a ‘laptop’ with a quantity of more than one, you can combine $elemMatch with other operators like $gt (greater than):

db.orders.find({
  "products": {
    "$elemMatch": {
      "name": "laptop",
      "quantity": { "$gt": 1 }
    }
  }
})

This query returns documents where at least one object in the products array meets all specified conditions.

Advanced Queries with Aggregation

For more complex scenarios, the MongoDB aggregation framework offers powerful tools. For instance, if you wish to count how many users have ‘coding’ as an interest, you can do the following:

db.users.aggregate([
  {"$match": {"interests": "coding"}},
  {"$count": "coding_enthusiasts"}
])

This pipeline first filters documents where ‘coding’ is in the interests array, then counts those documents. The result is a document with the number of coding enthusiasts.

Conclusion

Through this tutorial, we’ve explored several methods to find documents in MongoDB where an array contains a specific value. Starting from the basics, we moved to more complex scenarios involving nested arrays and aggregation. Mastering these techniques will significantly enhance your ability to query and analyze data in MongoDB.

Next Article: MongoDB: How to concatenate strings in aggregation pipeline (with examples)

Previous Article: MongoDB: Filter documents based on array length (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)