Kim
Kim

Reputation: 1081

Specific date comparison

Lets say I have an document like this:

{
    productName: 'soap',
    expiredDate: ISO_DATE_FORMAT
}

In normal sql I can query like this: SELECT * FROM table_name WHERE Month(expiredDate) = 11.

How to achieve it in mongoDB or mongooseJS?

Upvotes: 1

Views: 44

Answers (2)

chridam
chridam

Reputation: 103365

You could use the aggregation framework which has some operators that you can use. Consider the first use case which looks at manipulating the date operators within the $project pipeline and a subsequent $match pipeline to filter documents based on the additional field with the $month expression:

db.collection.aggregate([
    {
        "$project": {
            "productName": 1,
            "expiredDate": 1,
            "expiredMonth": { "$month": "$expiredDate" }
        }
    },
    { "$match": { "expiredMonth": 11 } }
])

Another option is using a single pipeline with $redact operator which incorporates the functionality of $project and $match as above and returns all documents which match a specified condition using $$KEEP system variable and discards those that don't match using the $$PRUNE system variable. Keep in mind this operator does a collection scan so the first pipeline option may be optimal:

db.collection.aggregate([
    {
        "$redact": {
            "$cond": [
                { 
                    "$eq": [
                        { "$month": "$expiredDate" }, 
                        11
                    ]
                }, 
                "$$KEEP", 
                "$$PRUNE"
            ]
        }
    }
])

Upvotes: 1

Parshuram Kalvikatte
Parshuram Kalvikatte

Reputation: 1646

You can use aggregation framework

db.collection.aggregate([{$project : {month  : {"$month" : $expiredDate},productName : 1,expiredDate:1},{$match : {month : 11}}])

Upvotes: 0

Related Questions