Sort array in MongoDB query and project all fields?

MongoDBDatabaseBig Data Analytics

To sort array, use $sort. For projection, use $project in MongoBD aggregate(). Let us create a collection with documents −

> db.demo252.insertOne(
...   {"Values" : [ { "v1" : 20, "v2" :30 }, { "v1" : 20, "v2" : 20 }, { "v1" : 10, "v2" : 7 } ] }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e46c2761627c0c63e7dba78")
}

Display all documents from a collection with the help of find() method −

> db.demo252.find();

This will produce the following output −

{ "_id" : ObjectId("5e46c2761627c0c63e7dba78"), "Values" : [ { "v1" : 20, "v2" : 30 }, { "v1" : 20, "v2" : 20 }, { "v1" : 10, "v2" : 7 } ] }

Following is the query to sort array and project all fields with aggregate() −

> db.demo252.aggregate([
...   { "$unwind": "$Values"},
...   { "$sort": {"Values.v2":1, "Values.v1": 1}},
...   { "$group": {
...      "_id": {
...         "_id": "$_id"
...
...      },
...      "st": { "$push":"$Values"}
...   }},
...   { "$project": {
...      "_id": "$_id._id",
...      "Values": "$st"
...   }}
...]);

This will produce the following output −

{ "_id" : ObjectId("5e46c2761627c0c63e7dba78"), "Values" : [ { "v1" : 10, "v2" : 7 }, { "v1" : 20, "v2" : 20 }, { "v1" : 20, "v2" : 30 } ] }
raja
Published on 30-Mar-2020 18:00:04
Advertisements