get value from a filter result match

48 Views Asked by At

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)

1

There are 1 best solutions below

0
Daniel On BEST ANSWER

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.