jjzjj

php - 按字段分组在 MongoDB 中不起作用

coder 2023-10-28 原文

我正在尝试计算数据库中所有记录的总和,我需要避免重复。我编写了这段代码来对记录进行分组,但它对我不起作用。

$pipeline = [
    ['$match' =>
            $criteria->getCondition()],
    ['$group' => 
            ['_id' => '$order_id', 'total' => ['$sum' => '$'.$column]]]
];

$this->getDbConnection()->aggregate('ticket_cache', $pipeline);

测试请求:

db.getCollection('ticket_cache').aggregate(
{
"$match":
    {"event_id":64}
},
{
    "$group" : 
        {"_id":"$order_id", "total": {"$sum":"$payment_amount"}}
})

结果:

/* 1 */
{
    "result" : [ 
        {
            "_id" : NumberLong(7002),
            "total" : 9000.0000000000000000
        }
    ],
    "ok" : 1.0000000000000000
}

数据库中的数据:

/* 1 */
{
    "result" : [ 
        {
            "_id" : ObjectId("553f8b4fbfabe2772f8b4f51"),
            "event_id" : NumberLong(64),
            "ticket_id" : NumberLong(8563),
            "ticket_code" : NumberLong(22062299),
            "ticket_type_id" : NumberLong(391),
            "ticket_created" : NumberLong(1430227620),
            "ticket_deleted" : NumberLong(0),
            "ticket_user_id" : NumberLong(2),
            "ticket_used" : NumberLong(0),
            "order_id" : NumberLong(7002),
            "order_code" : NumberLong(517005),
            "order_created" : NumberLong(1430227620),
            "order_deleted" : NumberLong(0),
            "order_sales_pipeline" : NumberLong(18),
            "order_invoice_id" : NumberLong(4202),
            "order_invoice_amount" : 3000.0000000000000000,
            "order_invoice_created" : NumberLong(1430227641),
            "order_invoice_deleted" : NumberLong(0),
            "order_invoice_code" : NumberLong(420155),
            "payment_id" : NumberLong(4365),
            "payment_amount" : 3000.0000000000000000,
            "payment_currency" : NumberLong(4),
            "payment_author_id" : NumberLong(1),
            "payment_type_id" : NumberLong(27),
            "payment_created" : NumberLong(1430227641),
            "payment_deleted" : NumberLong(0),
            "create_time" : ISODate("2015-04-28T13:29:51.328Z")
        }, 
        {
            "_id" : ObjectId("553f8b4fbfabe2772f8b4f4f"),
            "event_id" : NumberLong(64),
            "ticket_id" : NumberLong(8561),
            "ticket_code" : NumberLong(49287433),
            "ticket_type_id" : NumberLong(391),
            "ticket_created" : NumberLong(1430227620),
            "ticket_deleted" : NumberLong(0),
            "ticket_user_id" : NumberLong(2),
            "ticket_used" : NumberLong(0),
            "order_id" : NumberLong(7002),
            "order_code" : NumberLong(517005),
            "order_created" : NumberLong(1430227620),
            "order_deleted" : NumberLong(0),
            "order_sales_pipeline" : NumberLong(18),
            "order_invoice_id" : NumberLong(4202),
            "order_invoice_amount" : 3000.0000000000000000,
            "order_invoice_created" : NumberLong(1430227641),
            "order_invoice_deleted" : NumberLong(0),
            "order_invoice_code" : NumberLong(420155),
            "payment_id" : NumberLong(4365),
            "payment_amount" : 3000.0000000000000000,
            "payment_currency" : NumberLong(4),
            "payment_author_id" : NumberLong(1),
            "payment_type_id" : NumberLong(27),
            "payment_created" : NumberLong(1430227641),
            "payment_deleted" : NumberLong(0),
            "create_time" : ISODate("2015-04-28T13:29:51.316Z")
        }, 
        {
            "_id" : ObjectId("553f8b4fbfabe2772f8b4f50"),
            "event_id" : NumberLong(64),
            "ticket_id" : NumberLong(8562),
            "ticket_code" : NumberLong(24016753),
            "ticket_type_id" : NumberLong(391),
            "ticket_created" : NumberLong(1430227620),
            "ticket_deleted" : NumberLong(0),
            "ticket_user_id" : NumberLong(2),
            "ticket_used" : NumberLong(0),
            "order_id" : NumberLong(7002),
            "order_code" : NumberLong(517005),
            "order_created" : NumberLong(1430227620),
            "order_deleted" : NumberLong(0),
            "order_sales_pipeline" : NumberLong(18),
            "order_invoice_id" : NumberLong(4202),
            "order_invoice_amount" : 3000.0000000000000000,
            "order_invoice_created" : NumberLong(1430227641),
            "order_invoice_deleted" : NumberLong(0),
            "order_invoice_code" : NumberLong(420155),
            "payment_id" : NumberLong(4365),
            "payment_amount" : 3000.0000000000000000,
            "payment_currency" : NumberLong(4),
            "payment_author_id" : NumberLong(1),
            "payment_type_id" : NumberLong(27),
            "payment_created" : NumberLong(1430227641),
            "payment_deleted" : NumberLong(0),
            "create_time" : ISODate("2015-04-28T13:29:51.326Z")
        }
    ],
    "ok" : 1.0000000000000000
}

我哪里出错了?

最佳答案

你能试试下面的查询吗?它假定付款金额始终相同。看看 addToSet http://docs.mongodb.org/manual/reference/operator/update/addToSet/ .

db.getCollection('ticket_cache').aggregate( 
{ "$match": {"event_id":64} }, 
{ "$group" :
     {"_id":"$order_id", "total": {"$addToSet":"$payment_amount"}}
},     
{"$unwind": "$total"}, 
{"$group": {"_id": "null", "totalOdr": {"$sum": "$total"}}}
)

关于php - 按字段分组在 MongoDB 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29921321/

有关php - 按字段分组在 MongoDB 中不起作用的更多相关文章

  1. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  2. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  3. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  4. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  5. ruby-on-rails - s3_direct_upload 在生产服务器中不工作 - 2

    在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo

  6. ruby-on-rails - 在 Rails 和 ActiveRecord 中查询时忽略某些字段 - 2

    我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr

  7. ruby - 在 Ruby 中创建按公共(public)键值分组的新哈希 - 2

    假设我有一个在Ruby中看起来像这样的哈希:{:ie0=>"Hi",:ex0=>"Hey",:eg0=>"Howdy",:ie1=>"Hello",:ex1=>"Greetings",:eg1=>"Goodday"}有什么好的方法可以将它变成如下内容:{"0"=>{"ie"=>"Hi","ex"=>"Hey","eg"=>"Howdy"},"1"=>{"ie"=>"Hello","ex"=>"Greetings","eg"=>"Goodday"}} 最佳答案 您要求一个好的方法来做到这一点,所以答案是:一种您或同事可以在六个月后理解

  8. ruby-on-rails - Sphinx - 何时对字段使用 'has' 和 'indexes' - 2

    我几天前在我的ruby​​onrails2.3.2上安装了Sphinx和Thinking-Sphinx,基本搜索效果很好。这意味着,没有任何条件。现在,我想用一些条件过滤搜索。我有公告模型,索引如下所示:define_indexdoindexestitle,:as=>:title,:sortable=>trueindexesdescription,:as=>:description,:sortable=>trueend也许我错了,但我注意到只有当我将:sortable=>true语法添加到这些属性时,我才能将它们用作搜索条件。否则它找不到任何东西。现在,我还在使用acts_as_tag

  9. Ruby - 如何处理子类意外覆盖父类(super class)私有(private)字段的问题? - 2

    假设您编写了一个类Sup,我决定将其扩展为SubSup。我不仅需要了解你发布的接口(interface),还需要了解你的私有(private)字段。见证这次失败:classSupdefinitialize@privateField="fromsup"enddefgetXreturn@privateFieldendendclassSub问题是,解决这个问题的正确方法是什么?看起来子类应该能够使用它想要的任何字段而不会弄乱父类(superclass)。编辑:equivalentexampleinJava返回"fromSup",这也是它应该产生的答案。 最佳答案

  10. ruby-on-rails - 如何为空白字段编写 rspec? [Rails3.1] - 2

    我使用rails3.1+rspec和factorygirl。我对必填字段(validates_presence_of)的验证工作正常。我如何让测试将该事实用作“成功”而不是“失败”规范是:describe"Addanindustrywithnoname"docontext"Unabletocreatearecordwhenthenameisblank"dosubjectdoind=Factory.create(:industry_name_blank)endit{shouldbe_invalid}endend但是我失败了:Failures:1)Addanindustrywithnona

随机推荐