'mongodb nested schema - How to query a dynamic key
I have the following document structure,
{
"_id": "site1",
"loc_layout": [
{
"dynamic_key1": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
80.05204336806904,
13.131032427538385
]
},
"properties": {
"site": "site1",
"type": "gate",
"location": "sgate1"
}
}
],
"dynamic_key2": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
80.05204336804904,
13.13103242754358
]
},
"properties": {
"site": "site1",
"type": "gate",
"location": "sgate2"
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
80.05204336807904,
13.13103242753985
]
},
"properties": {
"site": "site1",
"type": "gate",
"location": "sgate3"
}
}
]
}
]
}
Above "dynamic_key1" & "dynamic_key2" are the dynamic key attributes. How to use this dynamic key to retrieve the required objects as an array.
I have tried with the below query,
collection.aggregate([
{
"$unwind": "$loc_layout"
},
{
"$match": {
"_id": "site1",
"loc_layout.dynamic_key1.properties.location": "sgate1"
}
},
{
"$project": {
"loc_layout": 1
}
}
])
The expected result is,
{
"_id": "site1",
"location_layout": [
{
"dynamic_key1": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
80.05204336806904,
13.131032427538385
]
},
"properties": {
"site": "site1",
"type": "gate",
"location": "sgate1"
}
}
]
}
]
}
Solution 1:[1]
You only need to $project the right field at the end, and no need for an $unwind too, this query get the result you're aiming to:
db.collection.aggregate([
{
"$match": {
"_id": "site1",
"loc_layout.dynamic_key1.properties.location": "sgate1"
}
},
{
"$project": {
"loc_layout.dynamic_key1": 1
}
}
])
You could have a look on attribute pattern btw as storing dynamic fields isn't a good practice when you need to filter on their content since you can create index on them
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 | Ayoub |
