Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Find Query by year [duplicate]

How to perform a find() operation with a condition like {fromdt: 2016} where fromdt is an ISODate in the backend. After checking stackoverflow posts, I could see only one option that uses $year with aggregation. But basically it uses projection and I dont get all fields in the document. So I would like to know how to achieve this without aggregation? Basically I want to apply the mentioned filter and get all documents with all fields in each.

example document:

{
"_id" : 501.0,
"custid" : 1.0,
"fromdt" : ISODate("2016-01-23T00:00:00.000Z"),
"enddt" : ISODate("2017-01-22T00:00:00.000Z")
}

Is there a better way without having to remember the format 2016-01-01T00:00:00.000Z by just giving the year value filter as 2016?

like image 556
Rahul Raj Avatar asked Dec 18 '22 00:12

Rahul Raj


1 Answers

You can try this, Date between 2016-01-01 to 2017-01-01

db.getCollection('TEST').find({
    "fromdt": {
        $gte: ISODate("2016-01-01T00:00:00.000Z"),
        $lt: ISODate("2017-01-01T00:00:00.000Z"),
    }
})
like image 63
Rahul Sharma Avatar answered Jan 02 '23 18:01

Rahul Sharma