【问题标题】:How to find the data by specific month in mongo db如何在mongodb中按特定月份查找数据
【发布时间】:2017-12-28 18:33:38
【问题描述】:
{ 
  "_id" : ObjectId("5a4212b49e710765c486d7c6"), 
  "student_id" : ObjectId("5a3df85bcc6425291c54d2ad"), 
  "attendance_status" : true, 
  "create_at" : 1514279592137.0, 
  "__v" : NumberInt(0)
}

{ 
  "_id" : ObjectId("5a4212b49e710765c486d7c7"), 
  "student_id" : ObjectId("5a3df85bcc6425291c54d2ae"), 
  "attendance_status" : true, 
  "create_at" : 1514279592137.0, 
  "__v" : NumberInt(0)
}

{ 
  "_id" : ObjectId("5a4212b49e710765c486d7c9"), 
  "student_id" : ObjectId("5a3df85bcc6425291c54d2b0"), 
  "attendance_status" : true, 
  "create_at" : 1514279592137.0, 
  "__v" : NumberInt(0)
}

我将创建时间存储为时间流逝。我想获取一个基于创建月份的数据,如何实现呢?

我正在尝试使用以下查询查找数据。

  Attendance.aggregate(
  [{
      $project: {
        create_at: "$create_at",
        student_id: "$student_id",
        attendance_status: "$attendance_status",
        month: {
          $month: "$create_at"
        }
      }
    },
    {
      $match: {
        "month": req.body.month
      }
    },
 ])

我想根据创建月份的输出。如果我发送 req.body.month=3。我只想要 3 个月内的数据。

【问题讨论】:

标签: node.js mongodb


【解决方案1】:

对于您想要查询数据的任何月份,您可以使用new Date('YYYY-MM-DD').getTime()获取开始时间戳和结束时间戳,并将数据库查询为

Attendance.find(
    {
     create_at: {
         $gte: s, //$gte corresponds to >=
         $lte: e  //$lte corresponds to <=
        }
    }
)

您可以找到有关此类 mongo 运算符的更多详细信息here


【讨论】:

    【解决方案2】:

    这样做,我想你应该看到MomentJS library。

    示例:

    var moment = require('moment');
    var month = 3; // March
    
    // Find all documents between 2017/03/01 and 2017/03/31
    Attendance.find({
        create_at: {
            $gte: moment(`2017/${month}`, 'YYYY/MM').startOf('month').format('x'),
            $lte: moment(`2017/${month}`, 'YYYY/MM').endOf('month').format('x')
        }
    });
    

    希望对你有帮助。

    【讨论】:

    • 我收到“MongoError: can't convert from BSON type double to Date”这个错误。
    • 您还在使用聚合?或者你正在使用查找请求?
    • 使用聚合
    猜你喜欢
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    相关资源
    最近更新 更多