Aggregation Frameworkは、このタイプのクエリに最適です。
以下にいくつかの例を示しました。
まず、いくつかのドキュメントを作成しましょう。
db.myDocumentCollection.insert({"date" : new Date('01/01/2012'), "topic" : "My Title 1"}); db.myDocumentCollection.insert({"date" : new Date('01/02/2012'), "topic" : "My Title 2"}); db.myDocumentCollection.insert({"date" : new Date('01/02/2012'), "topic" : "My Title 3"}); db.myDocumentCollection.insert({"date" : new Date('01/02/2012'), "topic" : "My Title 4"}); db.myDocumentCollection.insert({"date" : new Date('01/04/2012'), "topic" : "My Title 5"}); db.myDocumentCollection.insert({"date" : new Date('01/05/2012'), "topic" : "My Title 6"}); db.myDocumentCollection.insert({"date" : new Date(' 01/07/2013'), "トピック" : "私のタイトル 7"}); db.myDocumentCollection.insert({"date" : new Date('01/07/2013'), "topic" : "My Title 8"}); db.myDocumentCollection.insert({"date" : new Date('02/07/2013'), "topic" : "My Title 9"}); db.myDocumentCollection.insert({"date" : new Date('02/08/2013'), "topic" : "My Title 10"});
完全な日付でグループ化されたドキュメントの数を返す
db.myDocumentCollection.group(
{
$keyf : function(doc) {
return { "date" : doc.date.getDate()+"/"+doc.date.getMonth()+"/"+doc.date.getFullYear() };
},
initial: {count:0},
reduce: function(obj, prev) { prev.count++; }
})
出力
[
{
"date" : "1/0/2012",
"count" : 1
},
{
"date" : "2/0/2012",
"count" : 3
},
{
"date" : "4/0/2012",
"count" : 1
},
{
"date" : "5/0/2012",
"count" : 1
},
{
"date" : "7/0/2013",
"count" : 2
},
{
"date" : "7/1/2013",
"count" : 1
},
{
"date" : "8/1/2013",
"count" : 1
}
]
2013 年の日付ごとにグループ化されたドキュメントの数を返します
これはおそらく、実行したいクエリの種類にもう少し関連しています。
ここでは、 を使用して、2013年 1 月 1 日cond
以降のドキュメントをグループ化することのみを指定し
ます。$gte
$lte
db.myDocumentCollection.group(
{
$keyf : function(doc) {
return { "date" : doc.date.getDate()+"/"+doc.date.getMonth()};
},
cond: {"date" : {"$gte": new Date('01/01/2013')}},
initial: {count:0},
reduce: function(obj, prev) { prev.count++; }
})
出力
[
{
"date" : "7/0",
"count" : 2
},
{
"date" : "7/1",
"count" : 1
},
{
"date" : "8/1",
"count" : 1
}
]