Ad

Sort With Mongo And Return Specific ObjectId´s First

a structure like this: // (id´s simplified)

User:

{_id : ObjectId("4"), name: "Max Sampleman"}
{_id : ObjectId("5"), name: "Jon Doe"}

Books:

{_id : ObjectId("1"), title: "MongoDB Overview", "likes": 3, contributor: ObjectId("5") }
{_id : ObjectId("2"), title: "NoSQL Overview", "likes": 2, contributor: ObjectId("4")}
{_id : ObjectId("3"), title: "Tutorials Point Overview", "likes": 6, contributor: ObjectId("5")}

Now I'm looking for a way to find the books, sort them by likes, but return the ones from user 4 first.

An approach like this doesn't seem to work:

user4 = await User.findById(4)

books.find({}).sort({contributor: user4.id, likes: -1})

It returns an error, saying:

"message": "Invalid sort value: { contributor: 4 }"

Is there a way to achieve that kind of sorting?

Ad

Answer

The values allowed for sort are asc, desc, ascending, descending, 1, and -1, so you will not be able to pass the id instead of these values.

One way to achieve your requirement would be with aggregate and $set, You can add a new field and set it to true for the particular id you need to get first and use that field in while sorting.

books.aggregate([
    { $set: { priority: { $eq: ["$contributor", user4.id] } } },
    { $sort: { priority: -1, likes: -1 } },
  ]);;
Ad
source: stackoverflow.com
Ad