mongodb除了基本的查询功能,还提供了很多强大的聚合工具,其中简单的可计算集合中的文档个数,复杂的可利用MapReduce做复杂数据分析。
6.1 count
> db.foo.count() 9 > db.foo.find() { "_id" : ObjectId("5149af43ad11c9803e1781ea"),"bar" : "baz" } { "_id" : ObjectId("5149d1ffad11c9803e1781eb"),"xx" : 2 } { "_id" : ObjectId("514c7dce127bab4493992956"),"name" : "king","age" : 20 } { "_id" : ObjectId("514c7dda127bab4493992957"),"name" : "king1","age" : 25 } { "_id" : ObjectId("514c7de3127bab4493992958"),"name" : "king2","age" : 21 } { "_id" : ObjectId("514c85c1127bab4493992959"),"name" : 234,"age" : 30 } { "_id" : ObjectId("514d0c6be30a115bf216e111"),"name" : null,"age" : 28 } { "_id" : ObjectId("514d19c7e30a115bf216e114"),"apple" : 1,"banana" : 6,"peac h" : 3 } { "_id" : ObjectId("514d19fbe30a115bf216e115"),"apple" : 8,"spinach" : 4,"wat ermelon" : 3 } > db.foo.count({"name":"king"}) 1 |
6.2 distinct
找出给定键的所有不同的值,使用时不需指定集合和键。
> db.runCommand({"distinct":"foo","key":"name"}) { "values" : [ "king", "king1", "king2", 234, null ], "stats" : { "n" : 9, "nscanned" : 9, "nscannedObjects" : 9, "timems" : 58, "cursor" : "BasicCursor" }, "ok" : 1 } > db.runCommand({"distinct":"foo","key":"age"}) { "values" : [ 20, 25, 21, 30, 28 ], "timems" : 0, "ok" : 1 } |
有没有一种方法或得集合里面所有不同的键呢?起码没有内置的,不过可以用MapRedule.
6.3 group
先选定分组以来的键,然后mongodb就会将集合依据选定键值的不同分成若干组,然后可以通过聚合每一组内的文档,产生一个结果文档。
原文链接:https://www.f2er.com/javaschema/286388.html