我想在我的视图创建逻辑中添加一些新字段。但字段名将是一些现有字段的连接。基于某些条件,我需要在视图中添加这些字段
示例:data in my collection
{
data:{
computed_type:sleep
source:watch,
type:inBed,
value:60
}
}
我想在我的视图中添加字段->字段名:字段值
{
sleep_watch_inbed : 60
}
我试过这些,但不工作
project:{
dynamicKey: {
$map:{
input : { $objectToArray: "$data" },
as: "elem",
in: {
$cond: [
{
$eq: ["elem.computed_type", "sleep"],
},
{
$concat: [ "sleep_", 'elem.type',"_",'elem.source'
],
},
"$elem.computed_type",
]
}
}
}
}
不清楚要在哪里添加字段。可以是这个:
db.collection.aggregate([
{
$set: {
data: {
$concatArrays: [
{ $objectToArray: "$data" },
[{
k: { $concat: ["sleep_", "$data.type", "_", "$data.source"] },
v: "$data.value"
}]
]
}
}
},
{ $set: { data: { $arrayToObject: "$data" } } }
])
或:
db.collection.aggregate([
{
$set: {
dynamicKey: [
{
k: { $concat: ["sleep_", "$data.type", "_", "$data.source"] },
v: "$data.value"
}
]
}
},
{ $replaceWith: { $mergeObjects: ["$$ROOT", { $arrayToObject: "$dynamicKey" }] } },
{ $unset: "dynamicKey" }
])