通过共享字段进行组文档,同时还按日期进行过滤

发布于 2025-02-04 06:19:19 字数 583 浏览 1 评论 0原文

我有几个代表共享相同参考的交易的文档。但是,他们都可以有不同的日期。他们看起来有点像这样:

_id: ObjectId('xxxxxx')
reference: ObjectId('aaaaaa1')
amount: X
createdAt:2022-05-25T21:25:08.243+00:00

我需要对我的聚合限制日期限制,所以我写了一个$匹配阶段的

$match: {
createdAt: {
    $gte: ISODate('2022-01-01T00:00:00.000Z')

问题是,一旦我尝试添加小组阶段并总和所有金额(我会添加阶段下面)有些人可能会抛弃文件,如果同一购买的交易发生在选定的日期之后,而其他人则以前发生。我还尝试使用$ sort阶段(Createat:-1)与相同的不足结果

$group:{
_id: '$reference',
Total: {$sum:"$amount"}

我猜tl; dr:可以从特定日期开始对文档进行分组,同时确保每个共享参考字段的文档都与那些与该文档分组分享参考,尽管有时间差异? 提前致谢!

I have a several documents that represent transactions sharing the same reference. However, they all can have different dates. They would look kinda like this:

_id: ObjectId('xxxxxx')
reference: ObjectId('aaaaaa1')
amount: X
createdAt:2022-05-25T21:25:08.243+00:00

I need to put a date limit to my aggregation, so I wrote a $match stage

$match: {
createdAt: {
    $gte: ISODate('2022-01-01T00:00:00.000Z')

The issue is that once I try to add the group stage and sum all of the amounts (I'll add the stage below) some may leave a document behind, if a transaction attached to the same purchase happened after the date selected but others before. I also tried using a $sort stage (createdAt: -1) to the same underwhelming result

$group:{
_id: '$reference',
Total: {$sum:"$amount"}

I guess TL;DR: is it possible to group documents starting at a specific date while ensuring every document that shares the reference field is grouped with those that share Reference, despite their time difference?
Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

未蓝澄海的烟 2025-02-11 06:19:19

您需要首先使用$ group阶段,获取maxCreateDat,然后用$ match过滤它。

{
  '$group': {
    '_id': '$reference', 
    'maxCreatedAt': {
      '$max': '$createdAt'
    }, 
    'total': {
      '$sum': '$amount'
    }
  }
}, {
  '$match': {
    'maxCreatedAt': {
      '$gte': ISODate('2022-01-01T00:00:00.000Z')
    }
  }
}
}

You need to use $group stage first, get maxCreatedAt and then filter it with $match.

{
  '$group': {
    '_id': '$reference', 
    'maxCreatedAt': {
      '$max': '$createdAt'
    }, 
    'total': {
      '$sum': '$amount'
    }
  }
}, {
  '$match': {
    'maxCreatedAt': {
      '$gte': ISODate('2022-01-01T00:00:00.000Z')
    }
  }
}
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文