简体   繁体   中英

Mongoose + Aggregate Date Format Issue

When I perform following query in mongo, its working fine :

db.getCollection('patients').aggregate({
    "$match": {
    "demographics.dob": new Date("2018-01-17T00:00:00.000Z")
   }
})

But when I remove new Date() , its not working.

db.getCollection('patients').aggregate({
    "$match": {
    "demographics.dob": "2018-01-17T00:00:00.000Z"
   }
})

Now why I want to remove this is because when I'm trying to send date from express js, its going in string format, following is my code :

 filter["demographics.dob"] = new Date(filter["demographics.dob"]).toISOString();

I know that in aggregate, type casting is not done internally so please suggest me the way to do it in other way :)

Following is the result of mongoose debug log:

    patients.aggregate([
    {
        "$project": {
        "demographics.legalFirstName": "$demographics.legalFirstName",
        "demographics.lastName": "$demographics.lastName",
        "updatedAt": "$updatedAt",
        "_id": 1
        }
    },
    {
        "$match": {
        "$and": [
            {
            "demographics.dob": "2018-01-17T00:00:00.000Z"
            }
        ]
        }
    },
    {
        "$sort": {
        "updatedAt": -1
        }
    },
    {
        "$skip": 0
    },
    {
        "$limit": 2
    }
    ],
    , {}
    )

Use $dateFromString and change $match to use $expr in 3.6 version.

Something like

{"$match":{
  "$expr":{
  "$eq":[
    "$demographics.dob",
    {"$dateFromString":{"dateString":"2018-01-17T00:00:00.000Z"}}
  ]
  }
}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM