'filter object from array and select field
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"
Solution 1:[1]
There is an operator especially made for this
$elemMatch
The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.
db.orders.aggregate({ $match: { 'orderparameters.list': { $elemMatch: { name: "NEED_CUSTOMS_DOCUMENT", value: "True" } } } })
db.orders.find({ 'orderparameters.list': { $elemMatch: { name: "NEED_CUSTOMS_DOCUMENT", value: "True" } } })
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 | GCloony |
