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

后端 未结 2 2011
轻奢々
轻奢々 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:06

    You could use something like that

    db.getCollection('yourdocs').aggregate([
         { 
            $project: { 
                values: [ "$a", "$b" ] 
            } 
         },
         {
             $unwind: "$values"
         },
         {
             $group: {
                 _id: "distinctValues",
                 values: {
                     $addToSet: "$values"
                 }
             }
         }
    ])
    

    which will result in

    {
        "_id" : "distinctValues",
        "values" : [ 
            0, 
            1, 
            2, 
            3
        ]
    }
    

    Update: Just read you want it sorted which is not guaranteed with $addToSet. If sorting is crucial for you just add the following to the aggregation pipeline after the stages above

    {
        "$unwind": "$values"
    },
    {
        "$sort": { 
            "values": 1
        }
    },
    {
        "$group": { 
            _id: "distinctValues",
            "values": {
                "$push": "$values"
            }
        }
    }     
    

提交回复
热议问题