0

I have a collection on my db with a "created" field that is a timestamp.

What I need to do is somehow get the milliseconds on that timestamp, divide it by 10 and then floor it and THEN match it to a number.

What I'm trying to achieve with this is have a random spread of this documents into "batches" that range from 0-100.

Is there a way to do all this in one query? Basically something like:

Tried aggregation to add that field but then I'm getting all the documents and filtering, was wondering if there's a way to do all this "in-query"

collection.find({<created.convertToMilliseconds.divideByTen>: X }})
// X being any number from 0 to 100

I

  • There is a `$sample` operator to retrieve random records. https://stackoverflow.com/a/33578506/14955 – Thilo Oct 14 '19 at 09:36
  • In case you have a [Date](https://docs.mongodb.com/manual/reference/bson-types/#document-bson-type-date) field, you can extract the millisecond aspect of it using the Aggregation pipeline operator [$millisecond](https://docs.mongodb.com/manual/reference/operator/aggregation/millisecond/index.html) (this is used with the `$project` stage). You can follow this with a `$match` stage to get a specific range of documents. But, the `$sample` aggregation stage works fine too. – prasad_ Oct 14 '19 at 10:45

0 Answers0