How to Retrieve Only The Queried Element In An Object Array In MongoDB Collection

In this post, we will get to know the How to retrieve only the queried element in an object array in the MongoDB collection we could use the elemMatch operator in projection stageof the aggregation pipeline.

Retrieve

Retrieve Queried Elements

Here we have taken an example of a collection to explain evertings of the collection named user.

{
  "_id": ObjectId("12345"),
  "name": "John",
  "addresses": [
    {
      "type": "home",
      "street": "123 Main St",
      "city": "Anytown",
      "state": "CA",
      "zip": "12345"
    },
    {
      "type": "work",
      "street": "456 Broadway",
      "city": "Sometown",
      "state": "NY",
      "zip": "67890"
    }
  ]
}

In this above given example if we want to get specific object let here home address of john and for the same we had given an example of code below to understand it better.

db.users.aggregate([
  { $match: { name: "John" } },
  { $project: { address: { $elemMatch: { type: "home" } } } }
])

Where the function match is used for filtering the documents by the provided name as here “John” and the pipeline project only includes the field address where we found a match of the home address using the elemMatch operator. And at last, the result of the above code would be as followed given below.

{
  "_id": ObjectId("12345"),
  "address": {
    "type": "home",
    "street": "123 Main St",
    "city": "Anytown",
    "state": "CA",
    "zip": "12345"
  }
}

Here there are a few things we need to keep in mind that are there could be more than one or we can say multiple addresses that are matching the given query ‘elemMatch’ will return, when it is found at the first time means the first occurrence.

And to get all the occurrences of the field when ever it is found we can use another function that we call the filter operator.

We can also get the same result by using another operator that we call find() which is nothing but similar to that of finding a certain field and to implement the same we can follow the code given below to implement.

{
  "_id": ObjectId("12345"),
  "addresses": [
    {
      "type": "home",
      "street": "123 Main St",
      "city": "Anytown",
      "state": "CA",
      "zip": "12345"
    }
  ]
}

As the documents stored in the collection above, we have retrieved which is the only document we need so, n this way we can avoid a lot of data to e displayed instead of lot of data to be displayed we simply canalized it and only the required data will be displayed on the screen which we actually need for the requirements.

 

 

To learn more about retrieving only the queried element in an object array in the MongoDB collection visit:  by tutorial point.

To learn more about MongoDB and tutorial related to it visit: MongoDB Problems And Tutorials

Leave a Comment

%d bloggers like this: