通过共享字段进行组文档,同时还按日期进行过滤
我有几个代表共享相同参考的交易的文档。但是,他们都可以有不同的日期。他们看起来有点像这样:
_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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要首先使用
$ group
阶段,获取maxCreateDat
,然后用$ match
过滤它。You need to use
$group
stage first, getmaxCreatedAt
and then filter it with$match
.