Trinu
Trinu

Reputation: 1761

Fetch documents using createdAt mongodb

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();

Upvotes: 0

Views: 385

Answers (1)

J.F.
J.F.

Reputation: 15187

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);
});

Upvotes: 1

Related Questions