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

问题描述

我遇到了一些特殊目的的set操作实现,但对于一般情况没有任何帮助.执行集合操作(​​通常是交集,并集,对称差)的一般情况是什么?这很容易弄清楚在$ 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:

联盟-> ['红色','绿色','蓝色']

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

交叉点-> ['绿色']

Intersection --> ['green']

对称差异-> ['红色','蓝色']

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"]}]}
                 }
    }
]);

注意:有一个门票请求添加对称差异作为核心功能,而不必进行两个集合差异的并集.

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聚合用于通用集合操作(​​联合,交集,差异)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 16:31