mongodb - Mongo 中的两列分组

标签 mongodb aggregation-framework

假设在 mongo 中我有一个如下所示的集合:

+----+-----+-----+----------+
| id | x   | y   | quantity |
+----+-----+-----+----------+
| 1  | abc | jkl | 5        |
+----+-----+-----+----------+
| 2  | jkl | xyz | 10       |
+----+-----+-----+----------+
| 3  | xyz | abc | 20       |
+----+-----+-----+----------+

我想做一个 $group,其中 x 等于 y 并对数量求和。所以输出看起来像:

+-----+-------+
| x   | total |
+-----+-------+
| abc | 25    |
+-----+-------+
| jkl | 15    |
+-----+-------+
| xyz | 30    |
+-----+-------+

这可以在 mongo 中完成吗?

最佳答案

您不会执行 $group 来检索结果。您正在执行$lookup 。此功能是 MongoDB 3.2 中的新增功能。

使用您提供的示例数据,聚合如下:

db.join.aggregate( [
 { 
   "$lookup" : {
     "from" : "join",
     "localField" : "x", 
     "foreignField" : "y", 
     "as" : "matching_field"
   } 
 },
 {
   "$unwind" : "$matching_field"
 },
 {
   "$project" : {
     "_id" : 0,
     "x" : 1, 
     "total" : { "$sum" : [ "$quantity", "$matching_field.quantity"]}
   }
 }
])

示例数据集非常简单,因此您需要测试当返回的值不仅仅是一个简单结果等时的行为。

编辑:

如果 X 和 Y 之间可以有多个匹配,事情就会变得更加复杂。

// Add document to return more than a single match for abc
db.join.insert( { "x" : "123", "y" : "abc", "quantity" : 100 })

// Had to add $group stage to consolidate matched results 
db.join.aggregate( [
  { 
    "$lookup" : {
      "from" : "join",
      "localField" : "x", 
      "foreignField" : "y", 
      "as" : "matching_field"
    } 
  },
  {
    "$unwind" : "$matching_field"
  },
  { "$group" : { 
    "_id" : { "x" : "$x", "quantity" : "$quantity" },
    "matched_quantities" : { "$sum" : "$matching_field.quantity" }
  }},
  {
    "$project" : {
      "x" : "$_id.x", 
      "total" : { "$sum" : [ "$_id.quantity", "$matched_quantities" ]}
    }
  }
])

关于mongodb - Mongo 中的两列分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39399395/

相关文章:

php - MongoDB(或JSON)的Word Cities/Towns/Countries数据库?

node.js - 文件系统等重名功能

javascript - MongoDB:如何将数组的 $size 与另一个文档项进行比较?

javascript - Meteor SmartCollection 给出不一致的结果

node.js - 如何在 KeystoneJS 中创建唯一键

mongodb - 是否可以在 $regex [mongo db] 中使用 mongo 字段值作为模式?

mongodb - 如何使用MongoDB聚合进行分页?

node.js - mongodb 聚合 $lookup 与查找和填充

java - 返回唯一的mongo文档

java - 在 AWS 上部署 Java Web 应用程序 + MongoDB