0

I have a requirement to get a result out of mongodb in a specific format.

{
  "name": "name",
  "list": [
    {
      "id": "abcd1234",
      "obj": {
        "key": "abc"
      }
    },
    {
      "id": "abcd1234",
      "obj": {
        "key": "def"
      }
    },
    {
      "id": "abcd4321",
      "obj": {
        "key": "hij"
      }
    }
  ]
}

I need to query the db with filter {"list.id": "abcd1234"} and should get the result as a list where the projected field is "list.obj.key". So, in the above case, the output should be ["abc", "def"]

  • 1
    Does this answer your question? [Retrieve only the queried element in an object array in MongoDB collection](https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – Yong Shun May 22 '23 at 06:16

1 Answers1

0

To get the wanted result, you should the MongoDB aggregation pipeline

Your query would be something like:

db.<collection_name>.aggregate( [ { $unwind: { path: "$list" } }, {$match: {"list.id": "abcd1234"}}, {$project: { "_id": 0, "list.obj.key": 1 }}, { $group: { _id: null, result: { $push: "$list.obj.key" } } } ] ).next().result

To explain this in detail for each aggregation pipeline stage:

  1. You start with the $unwind function which extracts the list field to separate objects for each array value
  2. $match filters your results by the condition you wanted, in this case that the id matches abcd1234
  3. $project controls which results to return in the response, since _id is returned by default, we set that to 0, and we make sure that only the key value is returned in the list field
  4. $group: This stage groups the documents based on a specified _id value. In this case, since _id is set to null, it groups all documents into a single group. The $push operator is used to create an array (result) and push the values of list.obj.key for each document into the array.

Finally, the .next().result part of the query retrieves the result of the aggregation operation. Since we grouped all documents into a single group, there will be only one resulting document with the result field. Calling .next() retrieves that document, and .result accesses the value of the result field