Sergio Cano
Sergio Cano

Reputation: 760

Find documents in database by a date (year);

I am trying to make a query to my database, i have a collection with some documents that contains a field type Date, i would like to find all documents where the Date is equal to the year that i choose, what is the best way to do it?

At this moment i am receiving the documents like this.

facturasCtrl.filterDates = async (req, res) => {

    facturas = await facturasModel.find({ date: { '$gte': req.body.date1, '$lt': req.body.date2} })
    res.json(facturas); 
}

//date1 = 1.1.2018 //date2 = 31.12.2018

but i think this way is not correct at all... there is any method to find all documents from a date?

Upvotes: 1

Views: 254

Answers (1)

Ashh
Ashh

Reputation: 46461

You can use $expr with the $year aggregation operator

const year = 2018  

db.collection.find({ "$expr": { "$eq": [{ "$year": "$date" }, year] } })

Upvotes: 1

Related Questions