1

How do I query MongoDb for only today inserted Documents? My documents look like this

{
    "_id" : "8Mj3s6GRkvNeftbAP",
    createdAt: ISODate("2016-02-10T07:51:08.934Z"),
}

I tried {"createdAt": new Date()} which is not working probably due to time stamp. Please help

5
  • 1
    possible duplicate of stackoverflow.com/questions/11380428/… Commented Feb 15, 2016 at 7:30
  • hey hi , i need to dynamically generate date rages please help Commented Feb 15, 2016 at 7:38
  • where you got blocked? Commented Feb 15, 2016 at 7:40
  • i want to create a current date ISODate object which starts from 12 Am so that query will bring all the objects which are inserted today and this must be dynamic as this script will run every day Commented Feb 15, 2016 at 7:46
  • Data.now gives you the current date Commented Feb 15, 2016 at 7:50

1 Answer 1

1

When you query the collection for documents with createdAt equal to new Date() i.e. the current timestamp, you won't likely to get any result because the createdAt field will have values less than the current timestamp as time passes.

What you need is to query a date range that encompasses today, not the current date time. In other words, create a date object that represents that start of today, with that you can then query your collection for documents that have the createdAt field greater than that date. A mongo shell example follows:

var startOfToday = new Date();
startOfToday.setHours(0,0,0,0);

db.collection.find({ "createdAt": { "$gte": startOfToday } });

The above will query the collection for documents created today.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.