How to use MongoDB aggregation for general purpose set operations (union, intersection, difference)

前端 未结 2 1960
后悔当初
后悔当初 2021-01-02 03:45

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 (specific

2条回答
  •  礼貌的吻别
    2021-01-02 04:31

    Version 2.6+ Only:

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

    Union

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

    Intersection

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

    Relative Complement

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

    Symmetric Difference

    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.

提交回复
热议问题