简体   繁体   中英

How to automatically sort MongoDB arrays to be descending order by 2 certain fields with JavaScript

I am trying to sort MongoDB arrays to be in a descending order. I created some JavaScript code to take all the documents and turn them into JSON arrays, but i also need to sort them to be in a descending order. This is my code :

const result = xpSchema.find({
             gid: '754542598957432943',
        });
        
        jsonString = JSON.parse(JSON.stringify(result));
        console.log(jsonString);

The documents look like this:

 {
    xp: 5,
    coins: 0,
    level: 1,
    _id: '5f9337a49b46164777c46905',
    gid: '754542598957432943',
    profilepic: null,
    userId: '712947234886647828',
    username: 'CoolUserName',
    __v: 0
  }

And i need to sort them by the XP and Level fields. If the level is the same number as a different documents level, it needs to look at the XP and see what documents XP field is higher. And the highest one it needs to put on top.

Any ideas on how to do this ?

Thanks :)

Try with this query. To write a mongoose equivalent refer the docs.

https://mongoosejs.com/docs/api/aggregate.html

db.collection.aggregate([
  {
    "$match": {
      gid: "754542598957432943"
    }
  },
  {
    "$sort": {
      level: -1,
      xp: -1
    }
  }
])

Here is Mongo Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM