Mongodb string to date conversion

时光总嘲笑我的痴心妄想 提交于 2019-12-24 18:24:00

问题


Below is my sample mongodb collection

{
    "_id" : ObjectId("57ed32f4070577ec56a56b9f"),
    "log_id" : "180308",
    "issue_id" : "108850",
    "author_key" : "priyadarshinim_contus",
    "timespent" : NumberLong(18000),
    "comment" : "Added charts in the dashboard page of the application.",
    "created_on" : "2017-08-16T18:22:04.816+0530",
    "updated_on" : "2017-08-16T18:22:04.816+0530",
    "started_on" : "2017-08-16T18:21:39.000+0530",
    "started_date" : "2017-08-02",
    "updated_date" : "2017-08-02",
    "role" : "PHP",
    "updated_at" : ISODate("2017-09-29T15:27:48.069Z"),
    "created_at" : ISODate("2017-09-29T15:27:48.069Z"),
    "status" : 1.0
}

I need to get records with help of started_date , by default I will give two dates in that i will check $gt and $lt of started date .

        $current_date =  '2017-08-31';
        $sixmonthfromcurrent ='2017-08-01';

     $worklogs = Worklog::raw ( function ($collection) use ($issue_jira_id, $current_date, $sixmonthfromcurrent) {
     return $collection->aggregate ( [ 
              ['$match' => ['issue_id' => ['$in' => $issue_jira_id],
                          'started_date' => ['$lte' => $current_date,'$gte' => $sixmonthfromcurrent] 
                    ] 
              ],

              ['$group' => ['issue_id' => ['$push' => '$issue_id'],
                          '_id' => ['year' => ['$year' => '$started_date'],
                          'week' => ['$week' => '$started_date'],'resource_key' => '$author_key'],
                          'sum' => array ('$sum' => '$timespent')] 
              ],
              [ '$sort' => ['_id' => 1] 
              ] 
        ] );
     } );

If I run this query I am getting this type of error:

Can't convert from BSON type string to Date

How to rectify this error?


回答1:


The only field in your $group that I see as troubling is the field week. The year you could extract by doing a $project before your $group aggregation:

$project: {
        year: { $substr: [ "$started_date", 0, 4 ] }, 
        issue_id: 1,
        author_key: 1,
        timespent: 1
    }

if you know that the date string will always come at this format. Of course you cannot do a substr operation for finding out the week.

It would be easy though if your field started_date would be an actual ISODate(), then you could use exactly what you wrote as you probably already saw in the documentation. If you need the field week very bad, which I imagine you do, then I'd suggest you convert your field started_date to an ISODate(). You can do that with a bulkWrite:

db = db.getSiblingDB('yourDatabaseName');
var requests = [];
db.yourCollectionName.find().forEach(doc => { 
    var date = yourFunctionThatConvertsStringToDate(doc.started_date);
    requests.push( { 
        'updateOne': {
            'filter': { '_id': doc._id },
            'update': { '$set': {  
                "started_date": date
            } }
        }
    });
    if (requests.length === 500) {
        db.yourCollectionName.bulkWrite(requests);
        requests = [];
    }
});

if(requests.length > 0) {
     db.yourCollectionName.bulkWrite(requests);
}

Load this script directly on your mongodb server and execute there. Hope this helps.



来源:https://stackoverflow.com/questions/46603671/mongodb-string-to-date-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!