1

我有一個文件,它看起來像,MongoDB的組由UNIX時間和計數不工作

{ 
    "_id" : ObjectId("57dffd3b65291f06dab34385"), 
    "user" : "12345667890" 
    "time" : NumberLong(1474297140186) 
} 

我想計數的遊客人數爲某個特定應用。我有64個字段,我的查詢如下所示。

db.convo_log.aggregate([ 
    { 
     '$group': { 
      '_id': { 
       month: { $month: new Date("$time") }, 
       day: { $dayOfMonth: new Date("$time") }, 
       year: { $year: new Date("$time") } 
      }, 
      'count': { '$sum': 1 } 
     } 
    } 
]) 

即使我找了幾個組(因爲有來自不同天的數據),它返回的,

{ 
    "_id" : { 
     "month" : 8, 
     "day" : 17, 
     "year" : 292278994 
    }, 
    "count" : 64.0 
} 

這有什麼,我做錯了什麼?

+0

我沒有看到你的文檔中的'entry'領域:那麼與$dateToString運營商把這個完全,您可以運行這條管道來獲得期望的結果。您向我們展示的文件的預期結果是什麼?另外請注意,您無法以這種方式使用現有字段值創建新日期。 – styvane

+0

@Styvane對不起。我糾正了這個問題 – Dinal24

回答

2

您不能以這種方式從時間戳創建日期對象表示。您需要使用arithmetic operators進行一些算術運算,即$add對象構造函數的時間戳記,該對象構造函數將日期表示爲距離時期0毫秒(儘管以較短的形式)。

總和{ "$add": ["$time", new Date(0)] }產生新的日期對象。

db.convo_log.aggregate([ 
    { 
     "$project": { 
      "formattedDate": { 
       "$dateToString": { 
        "format": "%Y-%m-%d", 
        "date": { "$add": ["$time", new Date(0)] } 
       } 
      } 
     } 
    }, 
    { 
     "$group": { 
      "_id": "$formattedDate", 
      "count": { "$sum": 1 } 
     } 
    } 
])