[英]How to filter a collection based on each array item in a doc field in Mongodb
[英]MONGODB - adding a field in collection to a field in Item array
假設我有以下原型的文檔。
{
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 }
]
}
我的要求是獲取SKU“ XXX”的總價格為50 * 25(價格乘以數量)。 如何在MONGODB中獲得此查詢的結果?
db.YOUR_COLLECTION.aggregate({
$match: {
items.sku: "xxx"
},
$project: {
"product": {$multiply: ["$items.qty","$items.price"]},
_id: 0
}
});
我可以通過將查詢分為以下兩個塊來實現此目的的解決方案。
var pipe1 = [
{
{
“ $ unwind”:“ $ items”
},
$match: {
items.sku: "xxx"
},
$project: {
"product":
{
$ multiply:[“ $ items.qty”,“ $ items.price”]
},_id:0}}];
R = db.tb.aggregate(pipeline);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.