草庐IT

javascript - Mongodb $sum $cond 有两个条件

coder 2023-11-03 原文

我有一个聚合查询,它返回为给定位置提交的评论的总和/总数(不是平均星级)。评论评分为 1 - 5 星。这个特定的查询将这些评论分为两类,“内部”和“谷歌”。

我有一个查询返回的结果几乎是我正在寻找的结果。但是,我需要为内部审查添加一个附加条件。我想确保内部评论“stars”值存在/不为 null 并且包含至少 1 的值。所以,我想添加类似这样的东西会起作用:

{ "stars": {$gte: 1} }

这是当前聚合查询:

[
      {
        $match: { createdAt: { $gte: fromDate, $lte: toDate } }
      },
      {
        $lookup: {
          from: 'branches',
          localField: 'branch',
          foreignField: '_id',
          as: 'branch'
        }
      },
      { $unwind: '$branch' },
      {
        $match: { 'branch.org_id': branchId }
      },
      {
        $group: {
          _id: '$branch.name',
          google: {
            $sum: {
              $cond: [{ $eq: ['$source', 'Google'] }, 1, 0]
            }
          },
          internal: {            
            $sum: {
              $cond: [  { $eq: ['$internal', true]}, 1, 0 ],
            },
          }
        }
      }
]

chop 架构:

  {
    branchId: { type: String, required: true },
    branch: { type: Schema.Types.ObjectId, ref: 'branches' },
    wouldRecommend: { type: String, default: '' }, // RECOMMENDATION ONLY
    stars: { type: Number, default: 0 }, // IF 1 - 5 DOCUMENT IS A REVIEW
    comment: { type: String, default: '' },
    internal: { type: Boolean, default: true },
    source: { type: String, required: true },
  },
  { timestamps: true }

我需要确保我没有将“wouldRecommend”建议计入内部评论的总和。一定要确定某件事是否是评论,它将具有 1 星或更多星的星级。推荐的星级值为 0。

如何添加确保内部“$stars”值 >= 1(大于或等于 1)的条件?

使用 Ashh 的回答,我能够形成这个查询:

[
  {
    $lookup: {
      from: 'branches',
      localField: 'branch',
      foreignField: '_id',
      as: 'branch'
    }
  },
  { $unwind: '$branch' },
  {
    $match: {
      'branch.org_id': branchId
    }
  },
  {
    $group: {
      _id: '$branch.name',
      google: {
        $sum: {
          $cond: [{ $eq: ['$source', 'Google'] }, 1, 0]
        }
      },
      internal: {
        $sum: {
          $cond: [
            {
              $and: [{ $gte: ['$stars', 1] }, { $eq: ['$internal', true] }]
            },
            1,
            0
          ]
        }
      }
    }
  }
];

最佳答案

您可以使用 $and$cond运算符(operator)

{ "$group": {
  "_id": "$branch.name",
  "google": { "$sum": { "$cond": [{ "$eq": ["$source", "Google"] }, 1, 0] }},
  "internal": { "$sum": { "$cond": [{ "$eq": ["$internal", true] }, 1, 0 ] }},
  "rating": {            
    "$sum": {
      "$cond": [
        {
          "$and": [
            { "$gte": ["$stars", 1] },
            { "$eq": ["$internal", true] }
          ]
        },
        1,
        0
      ],
    }
  }
}}

关于javascript - Mongodb $sum $cond 有两个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56924668/

有关javascript - Mongodb $sum $cond 有两个条件的更多相关文章

  1. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  2. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  3. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  4. ruby - 定义方法参数的条件 - 2

    我有一个只接受一个参数的方法:defmy_method(number)end如果使用number调用方法,我该如何引发错误??通常,我如何定义方法参数的条件?比如我想在调用的时候报错:my_method(1) 最佳答案 您可以添加guard在函数的开头,如果参数无效则引发异常。例如:defmy_method(number)failArgumentError,"Inputshouldbegreaterthanorequalto2"ifnumbereputse.messageend#=>Inputshouldbegreaterthano

  5. ruby - 这两个 Ruby 类初始化定义有什么区别? - 2

    我正在阅读一本关于Ruby的书,作者在编写类初始化定义时使用的形式与他在本书前几节中使用的形式略有不同。它看起来像这样:classTicketattr_accessor:venue,:datedefinitialize(venue,date)self.venue=venueself.date=dateendend在本书的前几节中,它的定义如下:classTicketattr_accessor:venue,:datedefinitialize(venue,date)@venue=venue@date=dateendend在第一个示例中使用setter方法与在第二个示例中使用实例变量之间是

  6. ruby - 具有两个参数的 block - 2

    我从用户Hirolau那里找到了这段代码:defsum_to_n?(a,n)a.combination(2).find{|x,y|x+y==n}enda=[1,2,3,4,5]sum_to_n?(a,9)#=>[4,5]sum_to_n?(a,11)#=>nil我如何知道何时可以将两个参数发送到预定义方法(如find)?我不清楚,因为有时它不起作用。这是重新定义的东西吗? 最佳答案 如果您查看Enumerable#find的文档,您会发现它只接受一个block参数。您可以将它发送两次的原因是因为Ruby可以方便地让您根据它的“并行赋

  7. ruby-on-rails - 使用包含多个关联和单独的条件 - 2

    我的Gallery模型中有以下查询:media_items.includes(:photo,:video).rank(:position_in_gallery)我的图库模型有_许多媒体项,每个都有一个照片或视频关联。到目前为止,一切正常。它返回所有media_items包括它们的photo或video关联,由media_item的position_in_gallery属性排序。但是我现在需要将此查询返回的照片限制为仅具有is_processing属性的照片,即nil。是否可以进行相同的查询,但条件是返回的照片等同于:.where(photo:'photo.is_processingIS

  8. ruby-on-rails - 在 haml View 中重构条件 - 2

    除了可访问性标准不鼓励使用这一事实指向当前页面的链接,我应该怎么做重构以下View代码?#navigation%ul.tabbed-ifcurrent_page?(new_profile_path)%li{:class=>"current_page_item"}=link_tot("new_profile"),new_profile_path-else%li=link_tot("new_profile"),new_profile_path-ifcurrent_page?(profiles_path)%li{:class=>"current_page_item"}=link_tot("p

  9. ruby-on-rails - 使用 javascript 更改数据方法不会更改 ajax 调用用户的什么方法? - 2

    我遇到了一个非常奇怪的问题,我很难解决。在我看来,我有一个与data-remote="true"和data-method="delete"的链接。当我单击该链接时,我可以看到对我的Rails服务器的DELETE请求。返回的JS代码会更改此链接的属性,其中包括href和data-method。再次单击此链接后,我的服务器收到了对新href的请求,但使用的是旧的data-method,即使我已将其从DELETE到POST(它仍然发送一个DELETE请求)。但是,如果我刷新页面,HTML与"new"HTML相同(随返回的JS发生变化),但它实际上发送了正确的请求类型。这就是这个问题令我困惑的

  10. ruby-on-rails - 在具有 ActiveRecord 条件的相关模型中按字段排序 - 2

    我正在尝试按Rails相关模型中的字段进行排序。我研究的所有解决方案都没有解决如果相关模型被另一个参数过滤?元素模型classItem相关模型:classPriority我正在使用where子句检索项目:@items=Item.where('company_id=?andapproved=?',@company.id,true).all我需要按相关表格中的“位置”列进行排序。问题在于,在优先级模型中,一个项目可能会被多家公司列出。因此,这些职位取决于他们拥有的company_id。当我显示项目时,它是针对一个公司的,按公司内的职位排序。完成此任务的正确方法是什么?感谢您的帮助。PS-我

随机推荐