英文:
Is there any way to add dynamic field name in mongo DB aggregation.The field name is based on the data from the same collection
问题
{
"project": {
"dynamicKey": {
"$map": {
"input": { "$objectToArray": "$data" },
"as": "elem",
"in": {
"$cond": [
{
"$eq": ["elem.computed_type", "sleep"]
},
{
"$concat": ["sleep_", "elem.type", "_", "elem.source"]
},
"$elem.computed_type"
]
}
}
}
}
}
英文:
I want to add some new fields in my view creation logic.but the fields name will be concatenation of some existing field. so based on some condition i have to add those field in my view.
Example : data in my collection
{
data:{
computed_type:sleep
source:watch,
type:inBed,
value:60
}
}
I want to add field in my view with -> field name:field value
{
sleep_watch_inbed : 60
}
I have tried these, but not working
project:{
dynamicKey: {
$map:{
input : { $objectToArray: "$data" },
as: "elem",
in: {
$cond: [
{
$eq: ["elem.computed_type", "sleep"],
},
{
$concat: [ "sleep_", 'elem.type',"_",'elem.source'
],
},
"$elem.computed_type",
]
}
}
}
}
`
答案1
得分: 0
请查看以下代码段中的部分:
第一个代码段:
{
k: { $concat: ["sleep_", "$data.type", "_", "$data.source"] },
v: "$data.value"
}
第二个代码段:
{
k: { $concat: ["sleep_", "$data.type", "_", "$data.source"] },
v: "$data.value"
}
英文:
Not clear where you like to add the field. Could be this one:
db.collection.aggregate([
{
$set: {
data: {
$concatArrays: [
{ $objectToArray: "$data" },
[{
k: { $concat: ["sleep_", "$data.type", "_", "$data.source"] },
v: "$data.value"
}]
]
}
}
},
{ $set: { data: { $arrayToObject: "$data" } } }
])
or this:
db.collection.aggregate([
{
$set: {
dynamicKey: [
{
k: { $concat: ["sleep_", "$data.type", "_", "$data.source"] },
v: "$data.value"
}
]
}
},
{ $replaceWith: { $mergeObjects: ["$$ROOT", { $arrayToObject: "$dynamicKey" }] } },
{ $unset: "dynamicKey" }
])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论