Select 2 fields and return the sorted array with their different values

Say we have the following documents:

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

I need a query that will return:

[0, 1, 2, 3]

I want to know if there is a way to do this faster than:

  • just makes 2 requests, one selects a, the other selects b, then integrates into my application.
  • using map reduction (which was slow compared to the previous method)
+4
source share
2 answers

You need $groupour documents and use $pushto return the array "a" and "b" to the collection.

$project $setUnion, .

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

:

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

-

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

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

: , , , $addToSet. ,

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

All Articles