'Finding field name in MongoDB nested data
Is it possible to find the 'field name' using a regex first and then use that field name to find its value across all documents?
For example, if I have the following structure:
item : Object
- quantity: 50
- size: Object
- h: 20
Ideally, if I want the value of h, I would query item.quantity.size.h ("field.nestedField"). However, I only know the name 'h' but not what it is nested under. Is it possible to retrieve the entire field name (item.quantity.size.h) and its value (20)? I would then like to use that field name to obtain the value from all other documents.
Solution 1:[1]
Inspired by: MongoDB javascript `"$function"` not returning expected value in mongoplayground.net
You can use a $function aggregation, like this:
db.collection.aggregate([
{
$project: {
data: "$$ROOT"
}
},
{
"$project": {
"flattenKeys": {
"$function": {
"body": "function flatten(dataList, keysToHandle){while(keysToHandle.length){origKeyData = keysToHandle.shift();for (const newKey of Object.keys(origKeyData.objData)){keysToHandle.push({objData:origKeyData.objData[newKey],keyData:`${origKeyData.keyData}.${newKey}`});dataList.push(`${origKeyData.keyData}.${newKey}`);}}return dataList}",
"args": [
[],
[
{
objData: "$data",
keyData: "data"
}
]
],
"lang": "js"
}
}
}
},
{
$project: {
matchingKeys: {
$filter: {
input: "$flattenKeys",
as: "item",
cond: {
$regexMatch: {
input: "$$item",
regex: "keyD"
}
}
}
}
}
}
])
See how it works here
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 | nimrod serok |
