我有以下结构的集合
{
_id : ObjectId("52f0795a58c5061aa34d436a"),
"attribute1" : [1, 3, 6, 7],
"attribute2" : [2, 4, 6, 8]
}
有什么方法可以合并这两个属性,同时在 mongoDB 中使用聚合查询删除重复项?我需要这样的结果:
{
_id : ObjectId("52f0795a58c5061aa34d436a"),
"attribute3" : [1, 3, 6, 7, 2, 4, 8]
}
最佳答案
使用 .aggregate()
方法和 $setUnion
运营商。
db.collection.aggregate([
{ "$project": {
"attribute3": { "$setUnion": [ "$attribute1", "$attribute2" ] }
}}
])
产生:
{
"_id" : ObjectId("52f0795a58c5061aa34d436a"),
"attribute3" : [8, 4, 2, 6, 3, 7, 1]
}
关于mongodb - 合并mongoDB中的两个数组字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21545103/