2015-04-06 51 views
1

在我MongoDB的,我「由組」,試圖一組使用骨料()功能記錄和$比賽查詢我使用不會選擇管道中的記錄。

我的數據集有子文件(關於這一點我將$匹配),它看起來像這樣:

{ 
    "_id" : ObjectId("550994e21cba9597624195aa"), 
    "taskName" : "task name", 
    "taskDetail" : "task detail.", 
    "scheduledStartDate" : ISODate("2015-04-06T09:00:00.000Z"), 
    "scheduledEndDate" : ISODate("2015-04-06T11:00:00.000Z"), 
    "user" : { 
     "id" : "abcd1123", 
     "name" : "username" 
    }, 
    "status" : "Assigned" 
} 
{ 
    "_id" : ObjectId("550994e21cba9597624195aa"), 
    "taskName" : "task name", 
    "taskDetail" : "task detail.", 
    "scheduledStartDate" : ISODate("2015-04-06T09:00:00.000Z"), 
    "scheduledEndDate" : ISODate("2015-04-06T11:00:00.000Z"), 
    "user" : { 
     "id" : "abcd1123", 
     "name" : "username" 
    }, 
    "status" : "Assigned" 
} 
{ 
    "_id" : ObjectId("550994e21cba9597624195aa"), 
    "taskName" : "task name", 
    "taskDetail" : "task detail.", 
    "scheduledStartDate" : ISODate("2015-04-06T09:00:00.000Z"), 
    "scheduledEndDate" : ISODate("2015-04-06T11:00:00.000Z"), 
    "user" : { 
     "id" : "abcd1124", 
     "name" : "username" 
    }, 
    "status" : "Assigned" 
} 

我想找出的狀態計數的狀態類型分組的特定用戶。對於用戶「abcd1123」,查詢,我用的是:

db.tasks.aggregate([ 
    { 
     $match : { 
      user : { id : "abcd1123" } 
     } 
    }, 
    { 
     $group: { 
      _id: "$status", 
      count: { $sum: 1 } 
     } 
    } 
]) 

上面的查詢不返回任何結果,因爲$匹配不把任何結果進入管道。如果我修改這樣的查詢:

db.tasks.aggregate([ 
    { 
     $match : { 
      user : { id : "abcd1123", name : "username" } 
     } 
    }, 
    { 
     $group: { 
      _id: "$status", 
      count: { $sum: 1 } 
     } 
    } 
]) 

它的工作原理。但我沒有用戶名作爲輸入,我只需要根據用戶標識查找。

由於用戶不是陣列,我不能使用$ unwind就可以了。

我該如何實現這個目標?

回答

2

你太近只能改變你的聚集查詢,如下

db.collectionName.aggregate({ 
    "$match": { 
    "user.id": "abcd1123" 
    } 
}, 
{ 
    "$group": { 
    "_id": "$status", 
    "count": { 
     "$sum": 1 
    } 
    } 
}) 
+0

真棒。謝謝Yogesh。它非常完美! – Vijendran 2015-04-06 12:46:50