如何将 MongoDB 聚合用于通用集合操作(​​联合、交集、差异) [英] How to use MongoDB aggregation for general purpose set operations (union, intersection, difference)

查看:27
本文介绍了如何将 MongoDB 聚合用于通用集合操作(​​联合、交集、差异)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些特殊目的的集合操作实现,但一般情况下没有.执行集合操作的一般情况是什么(特别是交集、联合、对称差).在 $where 或 map reduce 中使用 javascript 更容易弄清楚,但我想知道如何在聚合中执行此操作以获得本机性能.

I have come across some special purpose implementation of set operations, but nothing for the general case. What is the general case for performing set operations (specifically intersection, union, symmetric difference). This is easier to figure out using javascript in a $where or map reduce, but I want to know how to do this in aggregation in order to get native performance.

用一个例子来说明这个问题的更好方法.假设我有 2 个数组/集的记录:

The better way to illustrate this question is with an example. Say I have a record with 2 arrays/sets:

db.colors.insert({
    _id: 1,
    left : ['red', 'green'],
    right : ['green', 'blue']
});

我想找到'left'和'right'数组的并集、交集和差异.更好的是,我想找到图片:

I want to find the union, intersection and difference of the 'left' and 'right' arrays. Even better, pictorially I want to find:

联合 --> ['red', 'green', 'blue']

Union --> ['red', 'green', 'blue']

交叉口 --> ['green']

Intersection --> ['green']

对称差分 --> ['red', 'blue']

Symmetric Difference --> ['red', 'blue']

推荐答案

仅限 2.6+ 版:

从 MongoDB 2.6 版开始,这变得容易得多.您现在可以执行以下操作来解决此问题:

As of version 2.6 of MongoDB, this has become much much easier. You can now do the following to solve this problem:

联合

db.colors.aggregate([
    {'$project': {  
                    union:{$setUnion:["$left","$right"]}
                 }
    }
]);

交叉口

db.colors.aggregate([
    {'$project': {  
                  int:{$setIntersection:["$left","$right"]}
                 }
    }
]);

相对补语

db.colors.aggregate([
    {'$project': {  
                    diff:{$setDifference:["$left","$right"]}
                 }
    }
]);

对称差分

db.colors.aggregate([
    {'$project': {  
                    diff:{$setUnion:[{$setDifference:["$left","$right"]}, {$setDifference:["$right","$left"]}]}
                 }
    }
]);

注意:有一个 ticket 要求将对称差异添加为核心功能,而不必将两组差异合并.

Note: There is a ticket requesting symmetric difference be added as a core feature rather than having to do the union of two set differences.

这篇关于如何将 MongoDB 聚合用于通用集合操作(​​联合、交集、差异)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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