本文介绍了在 MongoDB 中复制键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说明:我们如何复制字段 f1
.我想引入名为f2
的对象f1
的副本,查看预期输出
Explanation: How we can make a duplication of the field f1
. I want to introduce the replica of the object f1
that name as f2
, see the expected output
{
"data": [
{
"value": 100,
"fl" :1
},
{
"value": 300,
"fl" :0
},
{
"value": 14,
"fl" :0
},
{
"value": 3
"fl" :0
},
{
"value": 30,
"fl" :1
},
{
"value": 60,
"fl" :1
}
]
}
预期输出
{
"data": [
{
"value": 100,
"fl" :1,
"f2" :1
},
{
"value": 300,
"fl" :0,
"f2" :0
},
{
"value": 14,
"fl" :0,
"f2" :0
},
{
"value": 3,
"fl" :0,
"f2" :0
},
{
"value": 30,
"fl" :1,
"f2" :1
},
{
"value": 60,
"fl" :1,
"f2" :1,
}
]
}
推荐答案
查询
- 和前面的无条件类似,阅读
$map
文档,你就可以做到这些
- its similar with the previous here without condition, read
$map
documentation, you will be able to do all those
db.collection.aggregate([
{
"$set": {
"data": {
"$map": {
"input": "$data",
"in": {
"$mergeObjects": [
"$$m",
{
"f2": "$$m.fl"
}
]
},
"as": "m"
}
}
}
}
])
这篇关于在 MongoDB 中复制键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!