2017-10-06 176 views
0

下面是我的樣品MongoDB的收集MongoDB的字符串到日期的轉換

{ 
    "_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 
} 

我需要記錄與started_date的幫助下,在默認情況下我會以這兩個日期我會檢查$gt和開始$lt日期。

 $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] 
       ] 
     ]); 
    }); 

如果我運行此查詢我得到這種類型的錯誤:

Can't convert from BSON type string to Date 

如何糾正這個錯誤?

+0

「started_date」:「2017-08-02」不是類型ISODate(),看看你在數據庫中的類型,它應該是字符串。 $ lte和$ gte應該在匹配查詢中工作。但是,它會在$ group操作中引發異常,因爲您嘗試從字符串中提取一週。 –

+0

感謝您的回覆,如何在我的$ group操作中使用該字符串, – ganesh

回答

0

您的$ group我唯一看不到的地方就是。 的你可以通過你的$組聚集之前做一個$項目提取:

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

,如果你知道的日期字符串會經常來此格式。當然,你無法做一個substr操作來查找這個星期。

這將是容易但如果你的領域started_date將是一個實際ISODate(),那麼你可以使用你寫什麼,你可能已經在documentation看到。 如果你需要的場地本週非常糟糕,我想你會這樣做,那麼我建議你將你的場地started_date轉換爲ISODate()。直接

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); 
} 

加載這個腳本您的MongoDB的服務器上,並執行有: 你可以做與bulkWrite。 希望這有助於。