Hassaan
Hassaan

Reputation: 3991

How to filter a query on specific date format in mongodb?

I am getting date parameter in the string format 'yyyyMMdd'.

I have a collection in mongodb which has a property CallDate ISODate(), i need to write down a query which will filter the date parameter.

In SQL Server, we just use the query

select * from xyz x with (nolock) 
where CONVERT(VARCHAR(23), Cast(x.CallDate as datetime), 112)  = @pDateParameter

how could i achieve the same filter in mongodb

db.getCollection("_xyz").find({CallDate : ?}) //How to adjust that filter here

Upvotes: 2

Views: 699

Answers (1)

s7vr
s7vr

Reputation: 75934

You can try below aggregation in 3.4 version.

Use $addFields to add the string formatted date property followed by $match on date parameter and later if you prefer you can drop the string date column by using $project with exclusion.

db.collection.aggregate([
       { $addFields: {yearMonthDay: { $dateToString: { format: "%Y%m%d", date: "$CallDate" } } } },
       { $match: {"yearMonthDay":date parameter}},
       { $project:{"yearMonthDay":0}}
    ])

Upvotes: 1

Related Questions