0

I want to fetch the documents using createdAt filed in mongodb. Example i want to fetch the documents where today date is equal to createdAt.Attached is the screenshot. In the below case it should return 0.enter image description here I have tried using this but it is returning 1.

const todayAdded = await InventoryModel.find({
    owner: address, 
    "createdAt" : { 
      $gte: new Date("2016-11-16").toISOString(),
      $lte: new Date("2016-12-01").toISOString() 
    }
  }).estimatedDocumentCount();
Christian Fritz
  • 20,641
  • 3
  • 42
  • 71
Trinu
  • 1,721
  • 3
  • 21
  • 41
  • Could it be that you need to use an explicit `$and$ in the sub-conjunction, i.e., `createdAt: {$and: [ {$gte: ...}, {$lte: ... } ]}` ? – Christian Fritz Nov 01 '20 at 16:16
  • Thanks for your comment can you tell me where to add. If possible please add your code in my code. – Trinu Nov 01 '20 at 16:24
  • Does this answer your question? [Find objects between two dates MongoDB](https://stackoverflow.com/questions/2943222/find-objects-between-two-dates-mongodb) – Christian Fritz Nov 01 '20 at 16:48
  • See the duplicate. Your issue is the same as described in the first answer there. You are doing a string comparison because you converted the date to a string. – Christian Fritz Nov 01 '20 at 16:49

1 Answers1

1

Edit: I have seen the problem is estimatedDocumentCount() function.

As the documentation explain it will 'Returns the count of all documents in a collection or view'.

I think you expect the count from the query, not from the collection.

So, insted of estimatedDocumentCount() you have to use countDocuments(). By the way, if you check todayAdded.length it should be equal 0.

Try this query:

var result = await model.find({ 
  "owner": "...",
  "createdAt": { 
    "$gte": new Date(2016, 11, 16), 
    "$lt": new Date(2016, 12, 01) 
  }
}).countDocuments(function(err, count) {
      console.log("Number of docs: ", count);
});
J.F.
  • 13,927
  • 9
  • 27
  • 65
  • oh ya estimatedDocumentCount() returns all results where as countDocuments returns correct results – Trinu Nov 01 '20 at 16:51
  • Try using ```countDocuments``` instead of ```estimatedDocumentCount```. Since your problems is not querying the date but returning the total, I've edited the answer. – J.F. Nov 01 '20 at 16:52
  • Now i am getting 0 always const todayAdded = await InventoryModel.find({ owner: address, createdAt: { $gte: new Date(2019, 11, 1).toISOString(), $lt: new Date(2019, 11, 3).toISOString(), }, }).countDocuments(); It should return 1 – Trinu Nov 01 '20 at 16:59
  • Working fine now Thanks for your answer – Trinu Nov 01 '20 at 17:12