Syntax error How to sort by the difference in array contents in MongoDB?

How to sort by the difference in array contents in MongoDB?



To sort by difference, use aggregate() in MongoDB. Let us create a collection with documents −

> db.demo155.insertOne({"Scores":[{"Value":45},{"Value":50}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e354584fdf09dd6d08539e3")
}
> db.demo155.insertOne({"Scores":[{"Value":60},{"Value":10}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e35458efdf09dd6d08539e4")
}
> db.demo155.insertOne({"Scores":[{"Value":100},{"Value":95}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e354599fdf09dd6d08539e5")
}

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

> db.demo155.find();

This will produce the following output −

{ "_id" : ObjectId("5e354584fdf09dd6d08539e3"), "Scores" : [ { "Value" : 45 }, { "Value" : 50 } ] }
{ "_id" : ObjectId("5e35458efdf09dd6d08539e4"), "Scores" : [ { "Value" : 60 }, { "Value" : 10 } ] }
{ "_id" : ObjectId("5e354599fdf09dd6d08539e5"), "Scores" : [ { "Value" : 100 }, { "Value" : 95 } ] }

Following is the query to sort by the difference in array contents with MongoDB −

> db.demo155.aggregate([
...    { "$match": { "Scores.1": { "$exists": true } } },
...    { "$project": {
...       "Scores": "$Scores",
...       "sub": {
...          "$let": {
...             "vars": {
...                "f": { "$arrayElemAt": [ "$Scores", -2 ] },
...                "l": { "$arrayElemAt": [ "$Scores", -1 ] }
...             },
...             "in": { "$subtract": [ "$$l.Value", "$$f.Value" ] }
...          }
...       }
...    }},
...    { "$sort": { "sub": -1 } }
... ])

This will produce the following output −

{ "_id" : ObjectId("5e354584fdf09dd6d08539e3"), "Scores" : [ { "Value" : 45 }, { "Value" : 50 } ], "sub" : 5 }
{ "_id" : ObjectId("5e354599fdf09dd6d08539e5"), "Scores" : [ { "Value" : 100 }, { "Value" : 95 } ], "sub" : -5 }
{ "_id" : ObjectId("5e35458efdf09dd6d08539e4"), "Scores" : [ { "Value" : 60 }, { "Value" : 10 } ], "sub" : -50 }
Updated on: 2020-04-01T11:33:27+05:30

192 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements