2015-12-23 55 views
0

我有一些代碼,我設置了以下管道:過濾器集合,項目年&月,按年份分組&月,然後完成一個日期時間對象,如YYYY-MM-01。如何在pymongo管道內創建日期時間對象?

實例文檔:

{ 
    _id: 123456 
    foo: "bar" 
    dt: ISODate("2015-12-24T11:59:00Z") 
} 

示例代碼:

from pymongo import MongoClient 
db = client.testDB 
posts = db.testCollection 
pipeline = [ 
    {"$match": {"foo":"bar"}}, 
    {"$project": { 
     "year": {"$year": "$dt"}, 
     "month": {"$month": "$dt"}, 
    } 
    }, 
    {"$group": { 
     "_id": { "dt": ??? }, 
     "totalCount": { "$sum": 1 } 
    } 
    }, 
    {"$out": "myResults"} 
} 
posts.aggregate(pipeline) 

目標:

{ 
    _id: {dt: ISODate("2015-12-01T00:00:00Z")} 
    totalCount: 8 
} 

回答

0

爲了項目日期的第一個月,例如,變換2015-12-242015-12-01,我修改了code on this page如下:

例文獻:

{ 
    _id: 123456 
    foo: "bar" 
    dt: ISODate("2015-12-24T11:59:00Z") 
} 

代碼:

from pymongo import MongoClient 
db = client.testDB 
posts = db.testCollection 
pipeline = [ 
    {"$match": {"foo":"bar"}}, 
    { 
    "$project": { 
     "dt": "$dt" 
     "d": {"$dayOfMonth": "$dt"}, 
     "h": {"$hour": "$dt"}, 
     "m": {"$minute": "$dt"}, 
     "s": {"$second": "$dt"}, 
     "ml": {"$millisecond": "$dt"}, 
    } 
    }, 
    { 
    "$group": { 
     "_id": { 
     "$subtract": [ 
      "$dt", 
      { 
      "$add": [ 
       "$ml", 
       {"$multiply": ["$s", 1000]}, 
       {"$multiply": ["$m", 60, 1000]}, 
       {"$multiply": ["$h", 60, 60, 1000]}, 
       {"$multiply": [{"$subtract": ["$d", 1]}, 24, 60, 60, 1000]}, 
      ] 
      } 
     ] 
     }, 
     "totalCount": { "$sum": 1 } 
    } 
    }, 
    {"$out": "myResults"} 
} 
相關問題