2017-04-24 68 views
0

作为蒙戈文档中描述: 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 

以及等效蒙戈聚合查询如下:

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

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

+1

您的模式已经照顾'WHERE li.order_id = o.id',因为现在'$ items'是一个嵌入式文档。因此,当您使用订单项目保存订单文档时,建立这种关系。您可以$'放开'$ items'和'$ group'来计算其字段的'$ sum'。 – Veeram

+0

添加到Veeram的评论;所提供的sql查询是误导性的,因为WHERE子句应该是一个ON子句,作为两个sql表之间连接的一部分。一旦你意识到只有一个连接,并且没有真正的WHERE子句,这就解释了为什么你不需要等价的$匹配。 –

回答

3

@Veeram的评论是正确的。因为items列表被嵌入在订单采集,在关系数据库中,你会同时拥有一个orders表和orders_lineitem表(在https://docs.mongodb.com/manual/reference/sql-aggregation-comparison/从描述取的名字)

%的SQL中的where子句是不必要的例如数据,你开始像这样的文件:

{ 
    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"} ]) 

查询你得到的已经夷为平地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 } 
} 

,允许$group添加items.qty领域:

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

随着输出:

​​
相关问题