4

I wanted to find data for 2014-08-01 from MongoDB collection. Date in MongoDB is in ISO format.I wrote below query, but it gives me very huge number which i suspect is not the data for 1 day. Can some one let me know what is wrong with query. sd is the key

db.history.count({sd:{$gte: new Date("2014-08-01")},sd:{$lt:new Date("2014-08-01")}})

2 Answers 2

10

Ranges can be specified using $gte and $lt in the same document portion:

db.history.count({ "sd": {
    "$gte": new Date("2014-08-01"), "$lt": new Date("2014-08-02")
}})

Otherwise the argument are considered to be separate and a logical "and" condition. But really since you are using the same "key" in your "sd" field, this is not allowed in a JSON/BSON document and violates the "unique" keys rule for hash structures in general. So one condition overwrites the other and only one is applied.

That is why your result is wrong. Use as shown above instead.

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

2 Comments

Ofcourse it would violate unique key rule. Not sure how did i miss that. Thanks :)
@Neil I am having data for one month, I need to fetch maximum data for a specific date. ex: I need to fetch the maximum value for o5-Jan-2020 00:00:00 between 05-Jan-20200 23:59:59. How to achieve this condition
0
await model.find(
  {
    $or:
   [
     {
       createdDate:
      { $gte: new Date(startDate), $lte: new Date(endDate) },
     },
     {
       createdDate:
      { $gte: new Date(startDate), $lte: new Date(endDate).setDate(new Date(endDate).getDate() + 1) },
     },
   ],
  },
)

Please assign value to startDate and endDate. The above example will help to find different data from different date as well as the same date for example if your trying to fetch data from '2020-06-22' to '2020-07-02' you will get data from this date range, other your are trying to fetch data on the same date this code will work that mechanism also

Thank you

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.