簡體   English   中英

Mongodb字符串到日期的轉換

[英]Mongodb string to date conversion

以下是我的樣例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
}

我需要在starts_date的幫助下獲取記錄,默認情況下,我將給出兩個日期,因為我將檢查$gt$lt of start 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] 
              ] 
        ] );
     } );

如果我運行此查詢,則會出現此類型的錯誤:

Can't convert from BSON type string to Date

如何糾正此錯誤?

我認為您的$ group中唯一麻煩的字段是field week 通過在$ group聚合之前執行$ project可以提取的年份

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

如果您知道日期字符串將始終采用這種格式。 當然,您不能執行substr操作來找出星期。

這將是容易做的,如果你的領域started_date將是一個實際ISODate(),那么你可以使用你寫什么,你可能已經中看到文檔 如果您需要現場一周很糟糕,我想你這樣做,那么我建議你轉換你的領域started_date到ISODate()。 您可以使用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);
}

將此腳本直接加載到您的mongodb服務器上並在那里執行。 希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM