• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:8 mins read
You are currently viewing Retrieve Queried Element in an Object Array in MongoDB

How to retrieve only queried elements in an object array in MongoDB? The capability of MongoDB to store data in adaptable, schema-less documents is one of its most significant features. These documents might have arrays of embedded objects, which can occasionally make it hard to obtain certain elements from the array.

Advertisements

Although it can be difficult to retrieve a particular element from one of these arrays, there are some methods and operators we can use to retrieve it. In this piece of article, we will look at retrieving a queried element from a MongoDB object array.

1. Retrieve Queried Elements in an Object Array

In order to explain how to retrieve queried elements from a MongoDB object array, I will be using a students collection with some array data, so first let’s insert some data into the Students collection.

Here, we need to use MongoDB’s querying and projection features to retrieve specific elements within an object array. There are several operators available in MongoDB for querying and projecting array elements.

To begin with, let’s use a collection of students with fields status and an array of personal_details. Note that the personal_details is an array of objects, with each object having fields name, subject, age, and city.


# Insert sample data to collection
db.Students.insert([
{
  "_id": 1,
  "status": "students",
  "personal_details": [
    {
      "name": "Herley",
      "subject": "science",
      "age": 19,
      "city": "Georgia"
    },
    {
      "name": "Tyler",
      "subject": "computer",
      "age": 21,
      "city": "San Francisco"
    },
    {
      "name": "Jenna",
      "subject": "science",
      "age": 18,
      "city": "New York"
    }
  ]
}])

2. Use $elemMatch to Retrieve Queried Elements in an Object Array

To retrieve queried elements from a MongoDB object array you can use the $elemMatch operator. The $elemMatch operator is one of MongoDB’s most commonly used operators for querying object arrays. Moreover, it allows us to specify a query condition that must be satisfied by at least one element in the array.

Here, we have an example to get the personal details of the students whose city is New York. The $elemMatch operator finds the matching element within the array personal_details.


# Using #elemMatch
db.Students.find({ personal_details: 
    { $elemMatch: { city: "New York" } } 
  })

The above query returns the entire document in the output where at least one personal_details field has a city equal to “New York“.

MongoDB Retrieve Queried Elements

3. Retrieve Queried Element using the “$” positional operator

Now, if we want to retrieve only the personal_details object for each matched student from the object array. We can utilize the $ operator of MongoDB. The $ positional operator is used to project the first matching element of an array in MongoDB.

Also, it can be used to retrieve specific elements within an object array.

Consider the example where we specify that we want to include the personal_details field in the query results. But only the first matching element in the array. The $ operator here finds the matching element in the array.


# Using “$” positional operator
db.Students.find(
  { personal_details: { $elemMatch: { city: "New York" } } },
  { "personal_details.$": 1 }
)

The query result has only the matching element in the below output and not the entire personal_details array.

MongoDB Retrieve Queried Elements from object array

4. Retrieve Queried Element using the $filter operator

Moreover, we can also use the $filter operator to retrieve all the matching elements in the object array. Furthermore, The $filter operator gives an array of all the components which satisfy the given condition.

The example below shows the aggregation pipeline that creates a new field personal_details that contains only the elements in the personal_details array where the subject field is equal to “computer“. Here, the $filter operator is called to create the new array, and the $project stage is used to include only the personal_details field in the output.


# Using $filter operator
db.Students.aggregate([
  {
    $project: {
      _id: 1,
      personal_details: {
        $filter: {
          input: "$personal_details",
          as: "student_detail",
          cond: { $eq: [ "$$student_detail.subject", "computer" ] }
        }
      }
    }
  }
])

Following is the result displayed from the $filter query.

MongoDB Retrieve Queried Elements

5. By using the $unwind operator

Alternatively, we have the $unwind operator in MongoDB to complete this. The $unwind operator is used to create a new document for each element in an array. Implementing this to specific array elements can be helpful for queries and aggregations.

Here, we have used the aggregation pipeline to create a new document for each element in the personal_details array by using the $unwind operator, and then filtering the resulting documents to only include those with a city equal to “Georgia“.


# Using the $unwind operator
db.Students.aggregate([
  { $unwind: "$personal_details" },
  { $match: { "personal_details.city": "Georgia" } }
])

Yields below output.

MongoDB Retrieve Queried Elements

2. Conclusion

We can retrieve and manipulate data in MongoDB more successfully if we comprehend these methods and know how to use them. The $elemMatch operator and the $ positional operator are two of the most frequently used operators to retrieve queried elements in an object array in MongoDB. However, we have discussed a variety of other methods above which can be employed based on the particular requirements of our query.