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

查看:42
本文介绍了合并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]
}

推荐答案

如果你想修改你的数据,你可以使用 $addToSet$each 修饰符一旦您阅读了其中一个数组的内容.这些将是单独的更新,因为您不能在 更新操作.

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天全站免登陆