MongoDB学习笔记05

时间:2021-01-03 16:07:33

count 返回集合中文档数量文档数量

db.foo.count()
db.foo.count({"x":})

distinct用来找出给定键的所有不同的值,使用时必须指定集合和键

db.runCommand({"distinct":"person","key","age"})
db.person.distinct("age")

group的聚合要先选定分组所依据的键【键要是个对象才能返回所有的分组结果】,而后MongoDB就会将集合依据选定键值的不同分成若干组  condition 满足指定条件的文档

 db.runCommand({"group":{ "ns":"stocks", "key":{"day":true}, "initial":{"time":}, "$reduce":function(doc,prev){   if(d
oc.time>prev.time){ prev.price=doc.price; prev.time=doc.time; } }}}) db.runCommand({"group":{ "ns":"stocks", "key":"day", "initial":{"time":}, "$reduce":function(doc,prev){ if(d
oc.time>prev.time){ prev.price=doc.price; prev.time=doc.time; } }}})

ps:ns 指定要进行分组的集合 key 指定分组依据的键 initial 每一组reduce函数调用的初始时间,会作为初始文档传递给后续过程  $reduce 每个文档都对应一次这个调用

结果:

 {
"retval" : [
{
"day" : "2010/1/1",
"time" : "",
"price" :
},
{
"day" : "2010/1/2",
"time" : "",
"price" :
},
{
"day" : "2010/1/3",
"time" : "",
"price" :
}
],
"count" : NumberLong(),
"keys" : NumberLong(),
"ok" :
} {
"retval" : [
{
"time" : "",
"price" :
}
],
"count" : NumberLong(),
"keys" : NumberLong(),
"ok" :
}