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:
- You start with the $unwind function which extracts the list field to separate objects for each array value
- $match filters your results by the condition you wanted, in this case that the id matches abcd1234
- $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
- $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