2017-04-24 76 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"} 
     } 
    }]) 

隨着輸出:

​​
相關問題