I've got a list of objects with name value pairs in them and I can't figure out how to retrieve a value from an array where name is a certain value.
For instance:
{
"ordernumber" : "192915",
"orderparameters" : {
"list" : [
{
"composite" : null,
"name" : "CURRENCY_CODE",
"value" : "NOK",
"type" : "String"
},
{
"composite" : null,
"name" : "NEED_CUSTOMS_DOCUMENT",
"value" : "True",
"type" : "Boolean"
}
]}
}
Now I need to find the value of the item with
"name": "NEED_CUSTOMS_DOCUMENT"
so in this case
"value": "True"
I can list all the values with
db.orders.aggregate({ $match: { ordernumber:'1234' } }, { $project: { 'orderparameters.list.name': 1 } }).pretty()
But then how to retrieve the value field from the index with that name?
The index could be different on every document so I cant simply query "orderparameters.list.1.value"
CodePudding user response:
Refine your aggregate pipeline to include a another stage with a $filter
operator and that allows you to filter the list on a given condition, something like the following:
db.orders.aggregate([
{ $match: {
ordernumber: "1234",
"orderparameters.list.name": "NEED_CUSTOMS_DOCUMENT"
} },
{ $project: {
list: {
$filter: {
input: "$orderparameters.list",
cond: { $eq: ["$$this.name", "NEED_CUSTOMS_DOCUMENT"] }
}
}
} },
{ $project: { values: "$list.value" } }
])