我有包含日期的文件,我想知道如何按季度对它们进行分组?

我的模式是:

var ekgsanswermodel = new mongoose.Schema({
    userId: {type: Schema.Types.ObjectId},
    topicId : {type: Schema.Types.ObjectId},
    ekgId : {type: Schema.Types.ObjectId},
    answerSubmitted :{type: Number},
    dateAttempted : { type: Date},
    title : {type: String},
    submissionSessionId : {type: String}  
});

第一季度包括第1、2、3个月.第二季度包括第4、5、6个月,以此类推,直至第四季度.

我的最终结果应该是:

 "result" : [ 
   {
     _id: {
        quater:
     },
     _id: {
        quater:
     },
    _id: {
        quater:
     },
     _id: {
        quater:
     }
  }

推荐答案

您可以使用$cond操作员判断:

  • $month<= 3,用
  • $month<= 6,用
  • $month<= 9,用
  • 否则字段quarter的值将为"第四".
  • 然后是quarter区的$group.

代码:

db.collection.aggregate([
  {
    $project: {
      date: 1,
      quarter: {
        $cond: [
          { $lte: [{ $month: "$date" }, 3] },
          "first",
          {
            $cond: [
              { $lte: [{ $month: "$date" }, 6] },
              "second",
              {
                $cond: [{ $lte: [{ $month: "$date" }, 9] }, "third", "fourth"],
              },
            ],
          },
        ],
      },
    },
  },
  { $group: { _id: { quarter: "$quarter" }, results: { $push: "$date" } } },
]);

特定于您的模式:

db.collection.aggregate([
  {
    $project: {
      dateAttempted: 1,
      userId: 1,
      topicId: 1,
      ekgId: 1,
      title: 1,
      quarter: {
        $cond: [
          { $lte: [{ $month: "$dateAttempted" }, 3] },
          "first",
          {
            $cond: [
              { $lte: [{ $month: "$dateAttempted" }, 6] },
              "second",
              {
                $cond: [
                  { $lte: [{ $month: "$dateAttempted" }, 9] },
                  "third",
                  "fourth",
                ],
              },
            ],
          },
        ],
      },
    },
  },
  { $group: { _id: { quarter: "$quarter" }, results: { $push: "$$ROOT" } } },
]);

Mongodb相关问答推荐

如何将数组$拉到对象数组下

mongo如何通过聚合加载嵌套文档

使用 mongo-driver/mongo 使用键/值对中的值表达式查找文档

MongoDB 到 Snowflake 连续加载

使用 Spring Boot >= 2.0.1.RELEASE 将 ZonedDateTime 保存到 MongoDB 时出现 CodecConfigurationException

在 mongoDB 中存储 java 8 LocalDate

Mongo 可尾游标与 Redis 发布/订阅

如何在任意深度查找 MongoDB 字段名称

Mongoose Schema vs Mongo Validator

Mongoose 的保存回调是如何工作的?

带有 jQ​​uery Ajax/JSON 前端的 MongoDB 或 CouchDB 中间件

无法从 MongoDb C# 中的 BsonType ObjectId 反序列化字符串

为什么我新创建的 mongodb 本地数据库增长到 24GB?

指定在 mongodb .js 脚本中使用哪个数据库

mongoose:按字母顺序排序

RoboMongo:不显示所有文档

MongoDB 按数组元素对文档进行排序

如何在 golang 和 mongodb 中通过 id 查找

MongoDB Compass:select distinct field values

在mongoose中创建和查找地理位置