select 2 fields and return a sorted array with their distinct values

后端 未结 2 2010
轻奢々
轻奢々 2021-01-19 00:54

Say we have the following docs:

{a: 1, b: 2},
{a: 2, b: 0},
{a: 3, b: 1}

I want a query that will return:

[0, 1, 2, 3]
         


        
2条回答
  •  别那么骄傲
    2021-01-19 01:21

    You need to $group our documents and use the $push accumulator operator to return an array of "a" and "b" within the collection.

    In the $project operator you use the $setUnion operator to filter out the duplicates.

    db.coll.aggregate(
        [
            { "$group": { 
                "_id": null, 
                "a": { "$push": "$a" }, 
                "b": { "$push": "$b" } 
            }}, 
            { "$project": {
                "_id": 0, 
                "merged": { "$setUnion": [ "$a", "$b" ] } 
            }} 
        ]
    )
    

    which produces:

    { "merged" : [ 3, 2, 0, 1 ] }
    

提交回复
热议问题