簡體   English   中英

在 MongoDB + NodeJS 中僅按日期部分(沒有時間)分組

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

假設我們有查詢:

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

我按多個字段分組,我只想獲取InsertDate的日期部分而忽略時間。

我們怎么做?

我相信您的問題已在Group by Day of the Year下的 mongodb 文檔中得到解決:

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

您必須使用$dateToString將日期轉換為日期格式的字符串並將其添加到$group _id

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

我希望這有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM