【问题标题】:Why is $match not used in the Mongo Aggregation query?为什么在 Mongo 聚合查询中不使用 $match?
【发布时间】:2017-09-21 01:49:47
【问题描述】:

如 mongo 文档中所述: https://docs.mongodb.com/manual/reference/sql-aggregation-comparison/

有以下SQL查询的查询:

SELECT cust_id,
       SUM(li.qty) as qty
FROM orders o,
     order_lineitem li
WHERE li.order_id = o.id
GROUP BY cust_id

而等效的mongo聚合查询如下:

db.orders.aggregate( [
   { $unwind: "$items" },
   {
     $group: {
        _id: "$cust_id",
        qty: { $sum: "$items.qty" }
     }
   }
] )

但是,查询按预期工作正常。我的问题,为什么 SQL 中对应的 WHERE 子句没有 $match 子句? $unwind 如何补偿 $match 子句?

【问题讨论】:

  • 您的架构已经处理了WHERE li.order_id = o.id,因为现在$items 是一个嵌入文档的订单文档。因此,当您保存带有订单项目的订单文档时,就会建立这种关系。你$unwind$items$group来计算其字段的$sum
  • 添加到 Veeram 的评论中;所示的 sql 查询具有误导性,因为 WHERE 子句实际上应该是一个 ON 子句,作为两个 sql 表之间连接的一部分。一旦你意识到只有一个连接,没有真正的 WHERE 子句,这就解释了为什么你不需要一个等价的 $match。

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

@Veeram 的评论是正确的。 SQL 中的 where 子句是不必要的,因为 items 列表嵌入在 orders 集合中,在关系数据库中,您将同时拥有 orders 表和 orders_lineitem 表(名称取自https://docs.mongodb.com/manual/reference/sql-aggregation-comparison/)

根据示例数据,您可以从以下文档开始:

{
  cust_id: "abc123",
  ord_date: ISODate("2012-11-02T17:04:11.102Z"),
  status: 'A',
  price: 50,
  items: [ { sku: "xxx", qty: 25, price: 1 },
           { sku: "yyy", qty: 25, price: 1 } ]
}

当您$unwind 时,项目会展开,但其余数据会被投影。如果您运行类似

的查询
db.orders.aggregate([ {"$unwind": "$items"} ])

你得到输出

{
  cust_id: "abc123",
  ord_date: ISODate("2012-11-02T17:04:11.102Z"),
  status: 'A',
  price: 50,
  items: { sku: "xxx", qty: 25, price: 1 }
},
{
  cust_id: "abc123",
  ord_date: ISODate("2012-11-02T17:04:11.102Z"),
  status: 'A',
  price: 50,
  items: { sku: "yyy", qty: 25, price: 1 }
}

这将items 数组展平,允许$group 添加items.qty 字段:

db.orders.aggregate([ 
    {"$unwind": "$items"},
    {"$group": {
        "_id": "$cust_id",
        "qty": {"$sum": "$items.qty"}
       }
     }])

输出:

{ "_id": "abc123",
  "qty": 50
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-10
    • 1970-01-01
    • 2015-03-20
    • 2021-06-19
    • 1970-01-01
    • 2020-08-06
    相关资源
    最近更新 更多