在mongoDB中合并两个数组字段 [英] Merge two array field in mongoDB

查看:343
本文介绍了在mongoDB中合并两个数组字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下结构的集合

{
   _id : ObjectId("52f0795a58c5061aa34d436a"),
   "attribute1" : [1, 3, 6, 7],
   "attribute2" : [2, 4, 6, 8]
}

在mongoDB中使用聚合查询删除重复项时,有什么方法可以合并两个属性?我需要这样的结果:

Is there any way I can merge the two attributes while removing duplicates using aggregation query in mongoDB? I need the result to be like this:

{
   _id : ObjectId("52f0795a58c5061aa34d436a"),
   "attribute3" : [1, 3, 6, 7, 2, 4, 8]
}

推荐答案

如果要修改数据,可以使用 update 操作.

If you want to modify your data you can use $addToSet with the $each modifier once you have read the contents of one of the arrays. These would be individual updates as you cannot refer to another element of the document in an update operation.

如果您真的只是想进行汇总并可以等待,那么即将发布的MongoDB版本会添加新的将运算符设置为进行汇总.特别是有 $ setUnion 可以准确执行的操作你想要的.

If you really just want this for aggregation and can wait, then the upcoming release of MongoDB adds new set operators to aggregation. Particularly there is $setUnion which will do exactly what you want.

这篇关于在mongoDB中合并两个数组字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆