-2

In mongodb, documents have a property like this: dateOfPublication: 2021-04-09T21:25:05.612+00:00.

How can I get, say, the first 3 posts by time?

kertAW
  • 264
  • 3
  • 12
  • run a query sorted by dateOfPublication ascending then limit the results to 3. Docs can be a good starting place. – srknzl Apr 11 '21 at 16:09
  • what have you tried so far? – turivishal Apr 11 '21 at 16:12
  • @turivishal, that's the problem: I can't even imagine how this can be done – kertAW Apr 11 '21 at 16:29
  • no one can imagine, you need to search in google or stack overflow, see i found in this [question](https://stackoverflow.com/questions/17509025/how-do-you-tell-mongo-to-sort-a-collection-before-limiting-the-results) and you have to follow mongodb docs you will easily get in google just type in *mongodb find with sort and limit* – turivishal Apr 11 '21 at 16:35

1 Answers1

1

You can achieve this with aggregation. You need two staged:

  1. Sort your documents with $sort
  2. Limit your results to let's say 3 with $limit

Example:

db.collection.aggregate([
  {$sort: {'dateOfPublication': 1}},
  {$limit: 3}
])
gregooroo
  • 148
  • 1
  • 9