1

I am starting in the world of mongodb.

I have the following question:

I want to find the items that were posted from date x. In the records I have no date but I can get it from this statement:

ObjectId ("5ffdc390fdd1596ca5870bec"). GetTimestamp ()

whose result is: ISODate ("2021-01-12T15: 43: 12Z")

How could I create a query that returns all the records that were created from a given date, for example from 2021-01-12? Thank you very much.!

  • Does this answer your question? [Can I query MongoDB ObjectId by date?](https://stackoverflow.com/questions/8749971/can-i-query-mongodb-objectid-by-date) – Haniel Baez Feb 04 '21 at 17:09
  • No, I'm working only with mongodb and not from an app.I need only a mongodb query – Alberto Blanco Cala Feb 04 '21 at 17:12
  • I've found an alternative solution that is comparing with an oid created with a defined date to compare db.getCollection("files").find({"_id" : { $lte :ObjectId("6018c0300000000000000000") }}) It works but it's not the deffinitive solution – Alberto Blanco Cala Feb 04 '21 at 17:15

2 Answers2

2

The mongo Shell is an interactive JavaScript interface to MongoDB, so the solution by Leftium should work.

function objectIdWithTimestamp(timestamp) {
    /* Convert string date to Date object (otherwise assume timestamp is a date) */
    if (typeof(timestamp) == 'string') {
        timestamp = new Date(timestamp);
    }

    /* Convert date object to hex seconds since Unix epoch */
    var hexSeconds = Math.floor(timestamp/1000).toString(16);

    /* Create an ObjectId with that hex timestamp */
    var constructedObjectId = new ObjectId(hexSeconds + "0000000000000000");

    return constructedObjectId
}


/* Find all documents created between Jan 12th, 2021 and Jan 13th, 2021 */
db.mycollection.find({ _id: { $gt: objectIdWithTimestamp('2021/01/12'), $lt: objectIdWithTimestamp('2021/01/13')  } }); 
Haniel Baez
  • 1,646
  • 14
  • 19
1

You can query it directly:

db.collection.find({
  $expr: { 
     $gte: [ {$toDate: "$_id"}, ISODate("2021-01-01T00:00:00Z") ] }
  }
)

Usually I prefer the moment.js library, could be this for example:

db.collection.find({
  $expr: { 
     $gte: [ {$toDate: "$_id"}, moment().startOf('day').subtract(3, 'days').toDate() ] }
  }
)
Wernfried Domscheit
  • 54,457
  • 9
  • 76
  • 110
  • It doesn't work for me: db.fs.files.find({_id: {$lte: ISODate("2020-02-01T00:00:00+01:00")}}) --Fetched 0 record(s) in 27ms But there are many records that would be showed: db.getCollection("fs.files").count({"_id" : { $lte :ObjectId("6018c0300000000000000000")}}) --631 ObjectId("6018c0300000000000000000").getTimestamp() ---ISODate("2021-02-02T03:00:00Z") – Alberto Blanco Cala Feb 04 '21 at 17:26