【问题标题】:Categorise data according to date根据日期对数据进行分类
【发布时间】:2018-08-18 06:54:35
【问题描述】:

我有一个类似这样的 MongoDB 集合

const TransactionSchema = mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },
  transactionType: {
    type: String,
    enum: [transactionTypes.TRANSACTION_EXPENSE, transactionTypes.TRANSACTION_INCOME],
    required: true
  },
  amount: {
    type: Number,
    required: true
  },
  paymentType: {
    type: String,
    enum: [
      transactionPaymentTypes.PAYMENT_CARD,
      transactionPaymentTypes.PAYMENT_CASH
    ],
    required: true
  },
  createdDate: {
    type: Date,
    default: Date.now
  },
  description: String,
  tags: [String]
});

这代表两个用户之间的交易。 我想做的是按日期对数据进行分类。

所以如果我有 15-05-2018 的三笔交易和 16-05-2018 的四笔交易,我想将它们分组为

[
{
date: "15-05-2018",
transactions: [Transaction]
},
{
date: "16-05-2018",
transactions: [Transaction]
}
]

PS。为了方便起见,我写了 15-05-2018。实际上,数据将是一个时间戳。

如何做到这一点?

我搜索了一下,发现我们应该使用 mongoose/mongodb 的聚合功能,但我不明白如何使它工作。

注意: 我在 Mongoose 中使用 NodeJS、ExpressJS 和 MongoDB。

【问题讨论】:

标签: node.js mongodb express mongoose


【解决方案1】:

这是如何使用聚合框架来解决您在 mongoose 中的问题,因为您没有表示要匹配 Transaction 模型上的任何条件。您可以将日期格式化为您在问题中使用的示例。

Transaction.aggregate([
  { 
     "$addFields": {
        "createdDate": {
           $dateToString: { format: "%d-%m-%Y", date: "$createdDate" }
        }
     }
  },
  { 
     "$group": {
        "_id": { "$createdDate" },
        "transactions": {
            "$push": "$$ROOT"
        }
     }
  }])

这些是来自 mongodb 文档站点的一些参考资料,可帮助您更好地理解聚合。

DateToString、Group、Push

我还建议您在大多数参考资料中使用mongodb documentation site,因为它有很多有用的信息可以帮助您轻松理解这些概念。

【讨论】:

  • 谢谢。我会尝试一下。我真的不需要将日期转换为字符串。例如,我只是写了那个。我希望日期保持原样(时间戳)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-17
  • 1970-01-01
  • 2021-08-13
相关资源
最近更新 更多