简体   繁体   中英

Group by Date part only (without the time) in MongoDB + NodeJS

Suppose we have the query :

  EightWeekGamePlan.aggregate(
      [
        {
          $group: {
            _id: {
              LeadId: "$LeadId",
              Week: "$Week",
              InsertDate: "$InsertDate" ,   // I want to group by the date part
              Status: "$Status"
            },
            count: { $count: 1 }
          }
        },
        {
          $lookup: {
            from: "leads",
            localField: "_id",
            foreignField: "LeadId",
            as: "Joined"
          }
        },
        { $unwind: "$Joined" },
        { $replaceRoot: { newRoot: { $mergeObjects: ["$Joined", "$$ROOT"] } } },
        { $sort: { total: -1 } }
      ],
      function(err, results) {
        if (err) {
          console.log(err);
        }

        // ... do some manipulations ...

        console.log(_filtered);
        return res.json(_filtered);
      }
    );

I grouping by multiple fields and I want to take only the date part of InsertDate and disregard the time.

How can we do that ?

I believe your question is addressed in mongodb documentations under Group by Day of the Year :

https://docs.mongodb.com/manual/reference/operator/aggregation/group/

You have to convert the date into date-formatted string using $dateToString and add it to $group _id

_id : {$dateToString: { format: "%Y-%m-%d", date: "$InserDate" }}

I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM