Midhun Sudhakar
Midhun Sudhakar

Reputation: 1328

How to find documents in all mondays from last 7 weeks in mongodb

   {
    "_id" : ObjectId("568b650543712795bf864a45")
    "companyId" : "55e2d7cfdc8f74d14f5c900f",
    "timeStamp" : ISODate("2014-12-02T18:30:00.000Z")
   },
   {
    "_id" : ObjectId("568b650543712795bf864a46")
    "companyId" : "55e2d7cfdc8f74d14f5c900f",
    "timeStamp" : ISODate("2014-12-03T18:30:00.000Z")
 },
  {
    "_id" : ObjectId("568b650543712795bf864a47")
    "companyId" : "55e2d7cfdc8f74d14f5c900f",
    "timeStamp" : ISODate("2014-12-04T18:30:00.000Z")
 }

retrieve all documents in mondays from timeStamp field from last 7 weeks.

Upvotes: 2

Views: 1044

Answers (1)

Poorna Subhash
Poorna Subhash

Reputation: 2128

You have to use mongodb aggregation framework to achieve this.

Find date of start (current day - 7 weeks) in whatever programming language you are using. Then you have to use aggregation operation $dayOfWeek to achieve this


var pipeline = [
    {
      $match: {timeStamp: {$gte: startDate}}
    },
    {
      $project: {dayOfWeek: {$dayOfWeek: '$timeStamp'}} 
    },
    {
      $match: {dayOfWeek: 1}
    }
  ];
db.mycollection.aggreage(pipeline)
 

In above I have projected only one field, you may do project more fields.

For more information please click $dayOfWeek

Upvotes: 2

Related Questions