Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

charts - MongoDB $convert string

I'm planning to $convert my field to date because it is currently a string.

My Collection

"name": "Roboert Browning",
"delivery": [{
    "status": "Not Started",
    "createdAt": "$date": "2020-12-21T03:50:33.877Z",
    "updatedAt": "$date": "2020-12-21T03:50:33.877Z" 
}, {
    "status": "Accepted",
    "updatedAt": "$date": "2020-12-21T03:51:20.915Z",
    "createdAt": "$date": "2020-12-21T03:51:20.915Z"
}],
"price": 500,
"targetDate": "2020-12-08T11:50:15.659562",
"createdAt": 2020-12-08T11:36:48.285+00:00,
"updatedAt": 2020-12-09T12:02:06.426+00:00

I would like to match the createdAt to the targetDate if they are the same date, but it is currently a string. I want to convert the targetDate to Date so I can match them.

Current implementation

{
    $match: {
        "$expr": { 
            "$eq": [ 
                { "$dateToString": { "format": "%Y-%m-%d", "date": "$createdAt" } }, 
                { "$dateToString": { "format": "%Y-%m-%d", "date": "$targetDate" } }
            ] 
        } 
    }
}

I'm getting an error can't convert from BSON type string to Date


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

targetDate, createdDate are string fields

"createdAt": 2020-12-08T11:36:48.285+00:00,
"updatedAt": 2020-12-09T12:02:06.426+00:00

play

You can do as mentioned in playground i.e using toDate if your fields are really date field.

If they are already string, you don't need conversion.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...