'How to fetch the key value from an array in MongoDb?
I have the below document structure in MongoDB.
[
{
"network_type": "ex",
"rack": [
{
"xxxx": {
"asn": 111111,
"nodes": {
"business": [
"tt550abcc1eb01"
],
"master": [
"tt550abcc1eb02"
]
},
"region": "ex-01",
"zone": "01a"
},
"yyyy": {
"asn": 22222,
"nodes": {
"business": [
"er44abcc1eb28"
]
},
"region": "ex-02",
"zone": "02a"
}
}
]
}
]
The names inside nodes array of business, master are unique. Is it possible to find the nodes array details by just passing the value "er44abcc1eb28" ? I tried the below query but it didn't work out. Please help.
db.collection.find({"rack.$[].nodes.$[]": "er44abcc1eb28"},{})
Solution 1:[1]
db.collection.aggregate([
{ //Reshape the array
"$unwind": "$rack"
},
{
"$project": {
"racks": { //To handle dynamic key i.e xxxx, yyyy
"$objectToArray": "$rack"
}
}
},
{. //Reshape to match the element
$unwind: "$racks"
},
{
"$match": { //match condition
"racks.v.nodes.business": "er44abcc1eb28"
}
},
{
$group: { //Group the results incase there are more matches per id
"_id": "$_id",
data: {
$push: "$racks"
}
}
},
{
"$project": {
"rack": { //Reshape the data to the original form
"$arrayToObject": "$data"
}
}
}
]) //To understand, remove each stage and check, refer the documentation.
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 | Gibbs |
