'How to get a property value from an expression that evaluates to an object?
In an aggregation pipeline stage (for example $set), how could one get the value of an object property from an expression that evaluates to an object? Using MongoDB's (version 4.2) built in syntax and not plain JS.
For example when an expression evaluates to the object { k: "foo", v: "bar" }, how could one get the string bar? As there is no "get object property with name" aggregation pipeline operator/expression as far as I can see.
Solution 1:[1]
You could do that using $let:
{
$let: {
vars: {
expr: { k: "foo", v: "bar" } // Your expression here
},
in: "$$expr.v"
}
}
Would evaluate to "bar".
Solution 2:[2]
In MongoDB 5, you can use $getField to return a value of a specific field, where the field name can be any valid expression.
For older versions, the ticket for this feature describes an alternative: https://jira.mongodb.org/browse/SERVER-30417
Mongo 5:
db.foo.find()
{ _id: 1, a: 5, foo: { b: "a", c: 99.9 } }
db.foo.aggregate({$project:{ foo_c_is: {$getField:[ "c", "$foo" ] } } })
{ _id: 1, foo_c_is: 99.9 }
Aggregation workaround for 3.4.4 or later:
db.foo.aggregate({$project:{
foo_c_is:{$arrayElemAt:[
{$map:{
input:{$filter:{
input:{$objectToArray:"$foo"},
cond:{$eq:["$$this.k", {$literal:"c"}]}
}},
in:"$$this.v"
}},
0
]}
}})
{ "_id" : 1, "foo_c_is" : 99.9 }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | ekuusela |
