分享好友 数据库首页 频道列表

JavaScript按日期查询MongoDB中的数据的要点示例

MongoDB  2016-04-27 15:590

group by date 聚合查询日期 统计每天数据(信息量)

{ 
  "_id" : ObjectId("557ac1e2153c43c320393d9d"), 
  "msgType" : "text", 
  "sendTime" : ISODate("2015-06-12T11:26:26.000Z") 
} 

 

{ 
  "_id" : ObjectId("557ac1ee153c43c320393d9e"), 
  "msgType" : "text", 
  "sendTime" : ISODate("2015-06-12T11:26:38.000Z") 
} 

 

{ 
  "_id" : ObjectId("557ac2012de5d32d213963b5"), 
  "msgType" : "text", 
  "sendTime" : ISODate("2015-06-12T11:26:56.000Z") 
} 

 
4  

{ 
  "_id" : ObjectId("557ac978bb31196e21d23868"), 
  "msgType" : "text", 
  "sendTime" : ISODate("2015-06-12T11:58:47.000Z") 
} 

 

{ 
  "_id" : ObjectId("557ac9afbb31196e21d23869"), 
  "msgType" : "text", 
  "sendTime" : ISODate("2015-06-12T11:59:43.000Z") 
} 

  
 
SQL Here  

db.getCollection('wechat_message').aggregate( 
  [   
    {  $project : { day : {$substr: ["$sendTime", 0, 10] }}},     
    {  $group  : { _id : "$day", number : { $sum : 1 }}}, 
    {  $sort  : { _id : -1 }}     
  ] 
) 

  
 
Result Here 

"result" : [  
    { 
      "_id" : "2015-07-06", 
      "number" : 13.0000000000000000 
    },  
    { 
      "_id" : "2015-07-05", 
      "number" : 3.0000000000000000 
    },  
    { 
      "_id" : "2015-07-03", 
      "number" : 10.0000000000000000 
    },  
    { 
      "_id" : "2015-07-02", 
      "number" : 29.0000000000000000 
    }, 
]


查询某一天所有信息的3种方法,根据日期查询
mongodb的查询真让人难以琢磨,就查询单天信息,都需要花费一番功夫才行。 
 
第一种方式:  

coll.aggregate([ 
     {$project:{sendDate: {$substr: ['$sendTime', 0, 10]}, sendTime: 1, content:1}}, 
     {$match:{sendDate: '2015-07-05'}}, 
    ]) 

  
 
第二种方式(第一种的变异):  

coll.aggregate([ 
     {$match: {'sendTime': {'$gte': new Date('2015-07-05'), '$lt': new Date('2015-07-06')}}} 

 
第三中方式(第二种的变异): 

coll.aggregate([ 
     {$match: {'sendTime': {'$gte': new Date('2015-07-05 00:00:00'), '$lte': new Date('2015-07-05 23:59:59')}}} 

查询结果如下(展示一种方式:其他展示略有不同): 

[ { _id: 5599b09bc16aac90e9fb7995, sendDate: '2015-07-05' }, 
 { _id: 5599b161c16aac90e9fb7996, sendDate: '2015-07-05' }, 
 { _id: 5599b161c16aac90e9fb7997, sendDate: '2015-07-05' } ]  

查看更多关于【MongoDB】的文章

展开全文
相关推荐
反对 0
举报 0
评论 0
图文资讯
热门推荐
优选好物
更多热点专题
更多推荐文章
MongoDB服务端JavaScript脚本使用方法
这篇文章主要介绍了MongoDB服务端JavaScript脚本使用方法,需要的朋友可以参考下

0评论2015-11-0579

MongoDB中javascript脚本编程简介和入门实例
作为一个数据库,MongoDB有一个很大的优势——它使用js管理数据库,所以也能够使用js脚本进行复杂的管理——这种方法非常灵活

0评论2015-07-10120

更多推荐