Retrieve Only The Queried Elements In An Object Array in MongoDB Collection

In this post, we will learn to Retrieve only the queried elements in an object array in the MongoDB collection where we can use the elemMatch operator for getting the queried element in an element in an object array for a collection.

 

elements

 

Retrieve Queried Elements

Here we have given an example of executing it. And retrieve Only The Queried Element In An Object Array in MongoDB Collection from a database.

db. collection.find(
   { array field: { $elemMatch: { fieldToQuery: "valueToQuery" } } },
   { "array field.$": 1 }
)

Here we have used some terminology that is defined here.

  • The collection which is the name of the MongoDB collection.
  • Array Field is the name of the field that contains the object array.
  • Field to Query That is the name of the field within the object that you want to query.
  • Value to Query that is the value that you want to query for.

Here we have also used a function that is find() which is used to retrieve documents from the collection. The first argument of the Find method is the query, which uses the Element match operator to match the specified element in the object array. The second argument of the find() method that is the projection, which uses the $ (Dollar sign) operator to return only the queried element in the object array.

There are a few things that we need to keep in mind which follows as the function Element match operator returns only the first matching element in the object array. If you want to retrieve all matching elements in the object array, you can use the Agreement method with the Filter operator.

Even we get the same thing in MongoDB using an Aggregation frame work And for the same, we have given an example below which we can follow and implement as it is.

db.collection.aggregate([
   { $match: { arrayField.fieldToQuery: "valueToQuery" } },
   { $project: { _id: 0, queriedElement: { $filter: { input: "$arrayField", as: "element", cond: { $eq: [ "$$element.fieldToQuery", "valueToQuery" ] } } } } }
])

Here we have used aggregate() in a built method that performs aggregation operations on the collection. The $match stage in the program filters the documents in the collection to only include those that contain the queried element in the object array. The Project stage then creates a new field called Quried elements that uses the Filter operator to return only the queried element in the object array.

 

 

 

To learn more about Retrieve Only The Queried Element In An Object Array in MongoDB Collection visit:by  MongoDB Collection.

To learn more about MySQL tutorials and the solutions to the problems along with concepts and tutorials of solutions list and learn visit: MySQL Tutorials And Problems.

 

Leave a Comment

%d bloggers like this: