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

I store the creation time as times tramp. I want to get a data based on creation month.how to achieve it?

I am trying to find the data using the following query.

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

I want to the output based on the create month. If i send the req.body.month=3.I want the data in 3 month only.

Sakthivel
  • 139
  • 1
  • 16
  • can you be more specific about the question? what library are you using to query mongodb? what is the expected output? example would help. – Aniket Divekar Dec 26 '17 at 09:28
  • Possible duplicate of [How to convert milliseconds to date in mongodb aggregation?](https://stackoverflow.com/questions/29889719/how-to-convert-milliseconds-to-date-in-mongodb-aggregation) – s7vr Dec 26 '17 at 16:42

2 Answers2

4

For whatever month you want to query the data for, you can get start timestamp(s) and the end timestamp(e) by using new Date('YYYY-MM-DD').getTime()and query the db as

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

You can find more details about such mongo operators here


Aniket Divekar
  • 344
  • 1
  • 13
0

Do to that, I think you should see MomentJS library.

Exemple :

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')
    }
});

Hope it helps.

Sparw
  • 2,688
  • 1
  • 15
  • 34