Key examples of JavaScript querying the data in MongoDB by date


group by date aggregate query date statistics daily data (amount of information) 1

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

2

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

3

{
  "_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")
}

5

{
  "_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
    },
]

Three ways to query all information on a given day, based on the date The mongodb query is really hard to understand. It takes a lot of effort to query a single day’s information.

Method 1:

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

Type 2 (variation of type 1) :

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

Mode 3 (variation of type 2) :

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

The query results are as follows (one way to show it: the others are slightly different) :

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

0