A
A
Abdul Amenov2019-11-11 19:10:59
MongoDB
Abdul Amenov, 2019-11-11 19:10:59

How to sort in mongodb by condition?

Hello!
Do not judge strictly my question, I will try to convey the meaning as correctly as possible.
The task is this:
The database has a field with a date, if the date is greater than the current date, then the record in the database must be raised to the very top. Who knows how this can be done in MongoDB?
In Laravel I did this:

->orderByRaw('CASE WHEN top_date > NOW() THEN top_date END DESC')

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2019-11-12
@hzzzzl

record in the database must be raised to the very top

It is not clear, that is, that after the request, these records should be at the beginning of the returned result list?
so all the records in the database are in a conditionally random order
// выбрать нужные и отсортировать результат?
db.things.find({ 
  top_date: { $gt: new Date() } 
}).sort({ top_date: -1 })

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question