jjzjj

mongodb - $group by 8 记录聚合

coder 2023-11-03 原文

我有以下收藏

{
    "fare" : 12,
    "paymentMode" : "cash",
    "rideType" : "Self",
    "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
    "createdAt" : ISODate("2019-01-01T07:15:32.335Z")
},
{
    "fare" : 32,
    "paymentMode" : "cash",
    "rideType" : "Self",
    "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
    "createdAt" : ISODate("2019-01-01T07:15:32.335Z")
},
{
    "fare" : 12,
    "paymentMode" : "cash",
    "rideType" : "Self",
    "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
    "createdAt" : ISODate("2019-01-02T07:15:32.335Z")
},
{
    "fare" : 12,
    "paymentMode" : "cash",
    "rideType" : "Self",
    "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
    "createdAt" : ISODate("2019-01-03T07:15:32.335Z")
},
{
    "fare" : 12,
    "paymentMode" : "cash",
    "rideType" : "Self",
    "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
    "createdAt" : ISODate("2019-01-04T07:15:32.335Z")
},
{
    "fare" : 12,
    "paymentMode" : "cash",
    "rideType" : "Self",
    "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
    "createdAt" : ISODate("2019-01-05T07:15:32.335Z")
},
{
    "fare" : 12,
    "paymentMode" : "cash",
    "rideType" : "Self",
    "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
    "createdAt" : ISODate("2019-01-06T07:15:32.335Z")
},
{
    "fare" : 12,
    "paymentMode" : "cash",
    "rideType" : "Self",
    "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
    "createdAt" : ISODate("2019-01-07T07:15:32.335Z")
},
{
    "fare" : 12,
    "paymentMode" : "cash",
    "rideType" : "Self",
    "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
    "createdAt" : ISODate("2019-01-08T08:15:32.335Z")
},
{
    "fare" : 12,
    "paymentMode" : "cash",
    "rideType" : "Self",
    "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
    "createdAt" : ISODate("2019-01-09T08:15:32.335Z")
}

我需要进行聚合,将这些记录分成一对,每 8 条记录,并添加具有相同日期的记录的 fare。在上述日期中,2019-01-01 有两个票价

我的预期输出

{ data: [
{
    "fare" : 44,
    "paymentMode" : "cash",
    "rideType" : "Self",
    "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
},
{
    "fare" : 12,
    "paymentMode" : "cash",
    "rideType" : "Self",
    "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
    "createdAt" : ISODate("2019-01-02T07:15:32.335Z")
},
{
    "fare" : 12,
    "paymentMode" : "cash",
    "rideType" : "Self",
    "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
    "createdAt" : ISODate("2019-01-03T07:15:32.335Z")
},
{
    "fare" : 12,
    "paymentMode" : "cash",
    "rideType" : "Self",
    "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
    "createdAt" : ISODate("2019-01-04T07:15:32.335Z")
},
{
    "fare" : 12,
    "paymentMode" : "cash",
    "rideType" : "Self",
    "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
    "createdAt" : ISODate("2019-01-05T07:15:32.335Z")
},
{
    "fare" : 12,
    "paymentMode" : "cash",
    "rideType" : "Self",
    "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
    "createdAt" : ISODate("2019-01-06T07:15:32.335Z")
},
{
    "fare" : 12,
    "paymentMode" : "cash",
    "rideType" : "Self",
    "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
    "createdAt" : ISODate("2019-01-07T07:15:32.335Z")
},{
    "fare" : 12,
    "paymentMode" : "cash",
    "rideType" : "Self",
    "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
    "createdAt" : ISODate("2019-01-08T08:15:32.335Z")
}],
data:[{
    "fare" : 12,
    "paymentMode" : "cash",
    "rideType" : "Self",
    "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
    "createdAt" : ISODate("2019-01-09T08:15:32.335Z")
}
] }

最佳答案

您可以尝试以下聚合:

db.col.aggregate([
    {
        $group: {
            _id: { d: { $dayOfMonth: "$createdAt" }, m: { $month: "$createdAt" }, y: { $year: "$createdAt" } },
            fare: { $sum: "$fare" },
            paymentMode: { $first: "$paymentMode" },
            rideType: { $first: "$rideType" },
            userId: { $first: "$userId" },
            createdAt: { $first: "$createdAt" },
        }
    },
    {
        $sort: { createdAt: 1 }
    },
    {
        $project: {
            _id: 0
        }
    },
    {
        $group: {
            _id: null,
            docs: { $push: "$$ROOT" }
        }
    },
    {
        $project: {
            docs: {
                $map: {
                    input: { $range: [0,  { $ceil: { $divide: [ { $size: "$docs" }, 8 ] } } ] },
                    as: "arrayStart",
                    in: {
                        $slice: [ "$docs", { $multiply: [ "$$arrayStart", 8 ] }, 8 ]
                    }
                }
            }
        }
    },
    {
        $unwind: "$docs"
    }
])

基本上你想按天计算 fares 的总和,所以你需要使用 $dayOfMonth 根据日期类型获取那一天, $month$year运营商。然后您需要获得 8 元素的桶,以便您可以将所有文档合并到单个数组中($group_id 设置为 null)。然后你可以简单地计算出你需要多少个“桶”(使用 $ceil$divide )和 $slice长数组转换为 8 元素数组。在最后一步中,您可以使用 $unwind为每个最终文档获取 8 个元素的数组。输出:

{
    "_id" : null,
    "docs" : [
        {
            "fare" : 44,
            "paymentMode" : "cash",
            "rideType" : "Self",
            "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
            "createdAt" : ISODate("2019-01-01T07:15:32.335Z")
        },
        {
            "fare" : 12,
            "paymentMode" : "cash",
            "rideType" : "Self",
            "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
            "createdAt" : ISODate("2019-01-02T07:15:32.335Z")
        },
        {
            "fare" : 12,
            "paymentMode" : "cash",
            "rideType" : "Self",
            "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
            "createdAt" : ISODate("2019-01-03T07:15:32.335Z")
        },
        {
            "fare" : 12,
            "paymentMode" : "cash",
            "rideType" : "Self",
            "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
            "createdAt" : ISODate("2019-01-04T07:15:32.335Z")
        },
        {
            "fare" : 12,
            "paymentMode" : "cash",
            "rideType" : "Self",
            "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
            "createdAt" : ISODate("2019-01-05T07:15:32.335Z")
        },
        {
            "fare" : 12,
            "paymentMode" : "cash",
            "rideType" : "Self",
            "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
            "createdAt" : ISODate("2019-01-06T07:15:32.335Z")
        },
        {
            "fare" : 12,
            "paymentMode" : "cash",
            "rideType" : "Self",
            "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
            "createdAt" : ISODate("2019-01-07T07:15:32.335Z")
        },
        {
            "fare" : 12,
            "paymentMode" : "cash",
            "rideType" : "Self",
            "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
            "createdAt" : ISODate("2019-01-08T08:15:32.335Z")
        }
    ]
}
{
    "_id" : null,
    "docs" : [
        {
            "fare" : 12,
            "paymentMode" : "cash",
            "rideType" : "Self",
            "userId" : ObjectId("5c25c5fa12430a348459a3d7"),
            "createdAt" : ISODate("2019-01-09T08:15:32.335Z")
        }
    ]
}

关于mongodb - $group by 8 记录聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54035058/

有关mongodb - $group by 8 记录聚合的更多相关文章

  1. ruby - Sinatra:运行 rspec 测试时记录噪音 - 2

    Sinatra新手;我正在运行一些rspec测试,但在日志中收到了一堆不需要的噪音。如何消除日志中过多的噪音?我仔细检查了环境是否设置为:test,这意味着记录器级别应设置为WARN而不是DEBUG。spec_helper:require"./app"require"sinatra"require"rspec"require"rack/test"require"database_cleaner"require"factory_girl"set:environment,:testFactoryGirl.definition_file_paths=%w{./factories./test/

  2. ruby-on-rails - Rails 5 Active Record 记录无效错误 - 2

    我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa

  3. ruby-on-rails - 事件记录 : Select max of limit - 2

    我正在尝试将以下SQL查询转换为ActiveRecord,它正在融化我的大脑。deletefromtablewhereid有什么想法吗?我想做的是限制表中的行数。所以,我想删除少于最近10个条目的所有内容。编辑:通过结合以下几个答案找到了解决方案。Temperature.where('id这给我留下了最新的10个条目。 最佳答案 从您的SQL来看,您似乎想要从表中删除前10条记录。我相信到目前为止的大多数答案都会如此。这里有两个额外的选择:基于MurifoX的版本:Table.where(:id=>Table.order(:id).

  4. Ruby 守护进程导致 ActiveRecord 记录器 IOError - 2

    我目前正在用Ruby编写一个项目,它使用ActiveRecordgem进行数据库交互,我正在尝试使用ActiveRecord::Base.logger记录所有数据库事件具有以下代码的属性ActiveRecord::Base.logger=Logger.new(File.open('logs/database.log','a'))这适用于迁移等(出于某种原因似乎需要启用日志记录,因为它在禁用时会出现NilClass错误)但是当我尝试运行包含调用ActiveRecord对象的线程守护程序的项目时脚本失败并出现以下错误/System/Library/Frameworks/Ruby.frame

  5. ruby-on-rails - 在 Rails 中更高效地查找或创建多条记录 - 2

    我有一个应用需要发送用户事件邀请。当用户邀请friend(用户)参加事件时,如果尚不存在将用户连接到该事件的新记录,则会创建该记录。我的模型由用户、事件和events_user组成。classEventdefinvite(user_id,*args)user_id.eachdo|u|e=EventsUser.find_or_create_by_event_id_and_user_id(self.id,u)e.save!endendend用法Event.first.invite([1,2,3])我不认为以上是完成我的任务的最有效方法。我设想了一种方法,例如Model.find_or_cr

  6. ruby - 在模块/类之间共享全局记录器 - 2

    在许多ruby​​类之间共享记录器实例的最佳(正确)方法是什么?现在我只是将记录器创建为全局$logger=Logger.new变量,但我觉得有更好的方法可以在不使用全局变量的情况下执行此操作。如果我有以下内容:moduleFooclassAclassBclassC...classZend在所有类之间共享记录器实例的最佳方式是什么?我是以某种方式在Foo模块中声明/创建记录器还是只是使用全局$logger没问题? 最佳答案 在模块中添加常量:moduleFooLogger=Logger.newclassAclassBclassC..

  7. ruby - Sinatra 中的全局救援和日志记录异常 - 2

    如何在出现异常时指定全局救援,如果您将Sinatra用于API或应用程序,您将如何处理日志记录? 最佳答案 404可以在not_found方法的帮助下处理,例如:not_founddo'Sitedoesnotexist.'end500s可以通过调用带有block的错误方法来处理,例如:errordo"Applicationerror.Plstrylater."end错误的详细信息可以通过request.env中的sinatra.error访问,如下所示:errordo'Anerroroccured:'+request.env['si

  8. ruby-on-rails - 在不重新查询数据库的情况下重新排序 Rails 中的事件记录? - 2

    例如,假设我有一个名为Products的模型,并且在ProductsController中,我有以下代码用于product_listView以显示已排序的产品。@products=Product.order(params[:order_by])让我们想象一下,在product_listView中,用户可以使用下拉菜单按价格、评级、重量等进行排序。数据库中的产品不会经常更改。我很难理解的是,每次用户选择新的order_by过滤器时,rails是否必须查询,或者rails是否能够以某种方式缓存事件记录以在服务器端重新排序?有没有一种方法可以编写它,以便在用户排序时rails不会重新查询结果

  9. ruby-on-rails - ActiveRecord 如何将现有记录添加到 has_many :through relationship in rails? 中的关联 - 2

    在我的Rails项目中,我有三个模型:classRecipe:recipe_categorizationsaccepts_nested_attributes_for:recipe_categories,allow_destroy::trueendclassCategory:recipe_categorizationsendclassRecipeCategorization通过这个简单的has_many:through设置,我怎样才能像这样获取给定的食谱:@recipe=Recipe.first并根据现有类别向此食谱添加类别,并在相应类别上对其进行更新。所以:@category=#Exi

  10. ruby-on-rails - 使用 Rails 事件记录获取二级模型 - 2

    我有一个帖子属于城市的关系,城市又属于一个州,例如:classPost现在我想找到所有帖子及其所属的城市和州。我编写了以下查询来获取带有城市的帖子,但不知道如何在同一查找器中获取带有城市的相应州:@post=Post.find:all,:include=>[:city]感谢任何帮助。谢谢。 最佳答案 Post.all(:include=>{:city=>:state}) 关于ruby-on-rails-使用Rails事件记录获取二级模型,我们在StackOverflow上找到一个类似的问

随机推荐