Home > Net >  Mongo DB sort by calculated field
Mongo DB sort by calculated field

Time:10-12

I have users collection in mongo db. I want to sort the docs in the collection based on the delta between wins and losts In the case of the document below: 2-11 = -9

How do I do that? (I am using mongo from node js )

 {
  "_id": {
    "$oid": "615ebae9f5b277c71b886906"
  },
  "name": "jack",
  "wins": {
    "$numberInt": "2"
  },
  "losts": {
    "$numberInt": "11"
  },
  "lastVisit": {
    "$date": {
      "$numberLong": "1633852348009"
    }
  }
} 

CodePudding user response:

$sort doens't allow us to use an expression and sort by it so the only solution i think is to add one more field, sort by it and then removed it.

Query

  • on sort you can set it 1/-1 depending on the order you want
aggregate(
[{"$set": {"dif": {"$subtract": ["$wins", "$losts"]}}},
  {"$sort": {"dif": 1}},
  {"$unset": ["dif"]}])
  • Related