美文网首页
mongodb 聚合查询

mongodb 聚合查询

作者: 云龙789 | 来源:发表于2019-02-18 13:37 被阅读0次
{
   _id: ObjectId(7df78ad8902c)
   title: 'MongoDB Overview', 
   description: 'MongoDB is no sql database',
   by_user: 'runoob.com',
   url: 'http://www.runoob.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100
},
{
   _id: ObjectId(7df78ad8902d)
   title: 'NoSQL Overview', 
   description: 'No sql database is very fast',
   by_user: 'runoob.com',
   url: 'http://www.runoob.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 10
},
{
   _id: ObjectId(7df78ad8902e)
   title: 'Neo4j Overview', 
   description: 'Neo4j is no sql database',
   by_user: 'Neo4j',
   url: 'http://www.neo4j.com',
   tags: ['neo4j', 'database', 'NoSQL'],
   likes: 750
},
  • 现在我们通过以上集合计算每个作者所写的文章数,使用aggregate()计算结果如下:
> db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])
{
   "result" : [
      {
         "_id" : "runoob.com",
         "num_tutorial" : 2
      },
      {
         "_id" : "Neo4j",
         "num_tutorial" : 1
      }
   ],
   "ok" : 1
}
>

以上实例类似sql语句:

 select by_user, count(*) from mycol group by by_user

注意

经过多次测试,第一个参数键只能是 _id。我也不知道是为什么,后面的变量 num_tutorial 是聚合函数查到的结果值,这个变量应该是可以随便写的,但没有测试可不可以根数据变量一致

相关文章

网友评论

      本文标题:mongodb 聚合查询

      本文链接:https://www.haomeiwen.com/subject/mljaeqtx.html