1. count:
--这里是准备的测试数据
> db.test.remove()
> db.test.insert({"day" : "2012-08-20", "time" : "2012-08-20 03:20:40", "price" : 4.23})
> db.test.insert({"day" : "2012-08-21", "time" : "2012-08-21 11:28:00", "price" : 4.27})
> db.test.insert({"day" : "2012-08-20", "time" : "2012-08-20 05:00:00", "price" : 4.10})
> db.test.insert({"day" : "2012-08-22", "time" : "2012-08-22 05:26:00", "price" : 4.30})
> db.test.insert({"day" : "2012-08-21", "time" : "2012-08-21 08:34:00", "price" : 4.01})
--这里将用day作为group的分组键,然后取出time键值为最新时间戳的文档,同时也取出该文档的price键值。
> db.test.group( {
... "key" : {"day":true}, --如果是多个字段,可以为{"f1":true,"f2":true}
... "initial" : {"time" : "0"}, --initial表示$reduce函数参数prev的初始值。每个组都有一份该初始值。
... "$reduce" : function(doc,prev) { --reduce函数接受两个参数,doc表示正在迭代的当前文档,prev表示累加器文档。
... if (doc.time > prev.time) {
... prev.day = doc.day
... prev.price = doc.price;
... prev.time = doc.time;
... }
... } } )
[
{
"day" : "2012-08-20",
"time" : "2012-08-20 05:00:00",
"price" : 4.1
},
{
"day" : "2012-08-21",
"time" : "2012-08-21 11:28:00",
"price" : 4.27
},
{
"day" : "2012-08-22",
"time" : "2012-08-22 05:26:00",
"price" : 4.3
}
]
--下面的例子是统计每个分组内文档的数量。
> db.test.group( {
... key: { day: true},
... initial: {count: 0},
... reduce: function(obj,prev){ prev.count++;},
... } )
[
{
"day" : "2012-08-20",
"count" : 2
},
{
"day" : "2012-08-21",
"count" : 2
},
{
"day" : "2012-08-22",
"count" : 1
}
]
--最后一个是通过完成器修改reduce结果的例子。
> db.test.group( {
... key: { day: true},
... initial: {count: 0},
... reduce: function(obj,prev){ prev.count++;},
... finalize: function(out){ out.scaledCount = out.count * 10 } --在结果文档中新增一个键。
... } )
[
{
"day" : "2012-08-20",
"count" : 2,
"scaledCount" : 20
},
{
"day" : "2012-08-21",
"count" : 2,
"scaledCount" : 20
},
{
"day" : "2012-08-22",
"count" : 1,
"scaledCount" : 10
}
]