Question

I'm converting from MySql to MongoDB. Now I can't find a replace for this query:

(SELECT id, name, (score_kills - score_deaths) AS points FROM player ORDER BY points DESC LIMIT 10)
UNION
(SELECT id, name, (score_kills - score_deaths) AS points FROM player ORDER BY points ASC LIMIT 10);

This selects the 10 best and worst players sorted by the calculated field points. Can anyone help me with this?

The documents in player in MongoDB look like this:

{
    _id: ObjectId("1234567890"),
    name: "foo",
    score_kills: 321,
    score_deaths: 43
}
Was it helpful?

Solution

You can do this with aggregation framework. It won't be particularly efficient to do it in one query, so you should probably just do the same thing that you're doing in SQL which is running two queries - the only difference is that MongoDB won't "union" them for you, and you'll have to do it in the application.

The two aggregation queries would be:

db.collection.aggregate( [
        {$project:{name:1, points:{$subtract:["$score_kills","$score_deaths"]}}},
        {$sort:{points:-1}},
        {$limit:10}
]);

This would give you the top 10. To get the bottom 10 you would do the same thing but sort by {points:1} which will leave you with bottom 10.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top