Select two fields and return a sorted array with their distinct values in MongoDB?

MongoDBDatabaseBig Data Analytics

To select two fields and return a sorted array with distinct values, use aggregate framework along with $setUnion operator. Let us first create a collection with documents −

> db.sortedArrayWithDistinctDemo.insertOne(
...    { value1: 4, value2: 5}
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc690b99cb58ca2b005e666")
}
> db.sortedArrayWithDistinctDemo.insertOne(
...    {value1: 5, value2: 6}
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc690b99cb58ca2b005e667")
}
> db.sortedArrayWithDistinctDemo.insertOne(
...    {value1: 7, value2: 4}
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc690b99cb58ca2b005e668")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.sortedArrayWithDistinctDemo.find().pretty();

This will produce the following output −

{ "_id" : ObjectId("5cc690b99cb58ca2b005e666"), "value1" : 4, "value2" : 5 }
{ "_id" : ObjectId("5cc690b99cb58ca2b005e667"), "value1" : 5, "value2" : 6 }
{ "_id" : ObjectId("5cc690b99cb58ca2b005e668"), "value1" : 7, "value2" : 4 }

Following is the query to select two fields and return a sorted array with their distinct values. The fields here are “value1” and “value2” −

> db.sortedArrayWithDistinctDemo.aggregate(
...    [
...       { "$group": {
...          "_id": null,
...          "value1": { "$push": "$value1" },
...          "value2": { "$push": "$value2" }
...       }},
...       { "$project": {
...          "_id": 0,
...          "bothValues": { "$setUnion": [ "$value1", "$value2" ] }
...       }}
...    ]
... );

This will produce the following output. Now the sorted array is returned with distinct values −

{ "bothValues" : [ 4, 5, 6, 7 ] }
raja
Published on 21-May-2019 12:00:50
Advertisements