Search code examples
mongodbaggregation-frameworkmongodb-aggregation

get value from a filter result match


How do I get the value of a returned $filter match?

for example using this code ...

db.col.aggregate([
    {$project : {
        "Place"    : {$filter: {input: "$fields",as: "field",cond: { $eq: [ "$$field.name", "ABC" ]}}},
    }}
]);

I would get

[{"name":"ABC" ,"value":"DEF"}]

as the value of Place. I am wondering how to get just the value (DEF)


Solution

  • Thanks to the comment from Yogesh, figured it out

    db.col.aggregate([
        {$project : {
            "Place"    : {$filter: {input: "$fields",as: "field",cond: { $eq: [ "$$field.name", "Place" ]}}},
        }},
        {$project : {
            "Place"    : {$arrayElemAt : ["$Place.value",0]}
        }}
    ]);
    

    ..wondering if there is a way to single-project it.