MongoDB數(shù)據(jù)庫功能強(qiáng)大!除了基本的查詢功能之外,還提供了強(qiáng)大的聚合功能。這里簡(jiǎn)單介紹一下count、distinct和group。
--為了便于后面的測(cè)試,先清空測(cè)試集合。
> db.test.remove()
> db.test.count()
0
--插入4條測(cè)試數(shù)據(jù)。請(qǐng)留意Age字段。
> db.test.insert({"name":"Ada", "age":20})
> db.test.insert({"name":"Fred", "age":35})
> db.test.insert({"name":"Andy", "age":35})
> db.test.insert({"name":"Susan", "age":60})
--distinct命令必須指定集合名稱,如test,以及需要區(qū)分的字段,如:age。
--下面的命令將基于test集合中的age字段執(zhí)行distinct命令。
> db.runCommand({"distinct":"test", "key":"age"})
{
"values" : [
20,
35,
60
],
"stats" : {
"n" : 4,
"nscanned" : 4,
"nscannedObjects" : 4,
"timems" : 0,
"cursor" : "BasicCursor"
},
"ok" : 1
}
--這里是準(zhǔn)備的測(cè)試數(shù)據(jù)
> 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鍵值為最新時(shí)間戳的文檔,同時(shí)也取出該文檔的price鍵值。
> db.test.group( {
... "key" : {"day":true}, --如果是多個(gè)字段,可以為{"f1":true,"f2":true}
... "initial" : {"time" : "0"}, --initial表示$reduce函數(shù)參數(shù)prev的初始值。每個(gè)組都有一份該初始值。
... "$reduce" : function(doc,prev) { --reduce函數(shù)接受兩個(gè)參數(shù),doc表示正在迭代的當(dāng)前文檔,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
}
]
--下面的例子是統(tǒng)計(jì)每個(gè)分組內(nèi)文檔的數(shù)量。
> 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
}
]
--最后一個(gè)是通過完成器修改reduce結(jié)果的例子。
> db.test.group( {
... key: { day: true},
... initial: {count: 0},
... reduce: function(obj,prev){ prev.count++;},
... finalize: function(out){ out.scaledCount = out.count * 10 } --在結(jié)果文檔中新增一個(gè)鍵。
... } )
[
{
"day" : "2012-08-20",
"count" : 2,
"scaledCount" : 20
},
{
"day" : "2012-08-21",
"count" : 2,
"scaledCount" : 20
},
{
"day" : "2012-08-22",
"count" : 1,
"scaledCount" : 10
}
]