db.customer.insert([
{"_id": "C1",
"CUSTOMER" : { "customerId" : "C1",
"customerName" : "Tony",
"SHOPPINGCART":[{ "cartId" : "cart001",
"purchased": "no",
"containsProdList" : [
{ "prodListId" : 1,
"productId" : "P2",
"quantity" : 2 },
{ "prodListId" : 2,
"productId" : "P1",
"quantity": 1 } ]
},
{ "cartId" : "cart002",
"purchased": "yes",
"containsProdList" : [
{ "prodListId" : 1,
"productId" : "P2",
"quantity": 3 } ]
},
{ "cartId" : "cart006",
"purchased": "yes",
"containsProdList" : [
{ "prodListId" : 1,
"productId" : "P3",
"quantity": 3 } ]
} ]
}
},
{"_id":"C2",
"CUSTOMER" : { "customerId" : "C2",
"customerName" : "James",
"SHOPPINGCART":[
{ "cartId" : "cart003",
"purchased": "yes",
"containsProdList" : [
{ "prodListId" : 1,
"productId" : "P2",
"quantity" : 2 },
{ "prodListId" : 2,
"productId" : "P3",
"quantity": 1 } ]
},
{ "cartId" : "cart004",
"purchased": "no",
"containsProdList" : [
{ "prodListId" : 1,
"productId" : "P1",
"quantity": 3 } ]
},
{ "cartId" : "cart005",
"purchased": "no",
"containsProdList" : [
{ "prodListId" : 1,
"productId" : "P2",
"quantity": 1 } ]
}]
}
}
]);
上面的代碼是我的JSON格式的資料,我想提取同時購買“P1”和“P2”的客戶。
db.shoppingCart.aggregate([{
$unwind: {
path: '$CUSTOMER.creates.SHOPPINGCART'
}
}, {
$match: {
'CUSTOMER.creates.SHOPPINGCART.dateClosed': {
$ne: null
},
$and: [
{
'CUSTOMER.creates.SHOPPINGCART.containsProdList.productId': 'P1002'
},
{
'CUSTOMER.creates.SHOPPINGCART.containsProdList.productId': 'P1003'
}
]
}
}])
我寫了這樣的代碼,但是當 P2 和 P3 在同一個購物車中時(輸出只有 C2),我想找到購買的客戶而不管日期和購物車。
由于產品分別在C1 的cart002 和cart006 中,并且它們的采購值設定為yes,因此例外輸出為C1 和C2。C2 在同一個購物車和產品串列中有兩種產品。
我需要你們的幫助,伙計們!
uj5u.com熱心網友回復:
假設我們要查找購買了 P1 和 P2(或任意數量)產品但在同一個購物車中的客戶。這是一個沒有特征的解決方案,$unwind因此即使使用大型SHOPPINGCART.
一開始要理解這里發生的事情并不容易,但是
如果你從“深度”而不是自上而下看它會有所幫助。
- 我們想要找到同時包含 P1 和 P2 的購物車,所以我們想要過濾
它。為了使它更通用一些,我們將
使用 ["P1","P2"]設定一個目標陣列變數 "targs" - 我們將使用
$map作為獲取CUSTOMER.SHOPPINGCART陣列
并將其傳遞給的方法$filter - 后面的陣列
$filter將包含 0 到 n 個專案;我們
使用$size運算子獲取長度并在 中捕獲它npids。 - 我們現在有一個
{cartId,npids}物件陣列...... - ...我們將其用作“外部”的輸入,
$filter以僅保留
npids == targs.length 的那些物件,這意味著所有產品都
出現在該購物車中。 - 整個事情被投影為
XX。 - 許多檔案不會有任何匹配項并且
XX大小為 0。我們
可以使用它們$match來消除這些。
var targs = ["P1","P2"];
db.shoppingCart.aggregate([
{$project: {
XX: {$filter: {input: // the "outer" filter
{$map: {input: "$CUSTOMER.SHOPPINGCART", as:"z", in: {
cart: "$$z.cartId",
npids: {$size: {$filter: {input: "$$z.containsProdList", // inner filter
as: "z2",
cond: {$in:["$$z2.productId",targs]} // the heart of the matter
}}
}
} }},
as: "z3",
cond: {$eq:["$$z3.npids",targs.length]}
}}
}}
,{$match: {$expr: {$gt:[{$size: "$XX"},0]} }}
]);
uj5u.com熱心網友回復:
如果我理解你,你想提取所有購買了 productId "P1" 和 "P2" 的客戶;如果是這種情況,您可以像這樣進行查詢:
db.collection.find({
$and: [
{
"CUSTOMER.SHOPPINGCART.containsProdList.productId": "P1"
},
{
"CUSTOMER.SHOPPINGCART.containsProdList.productId": "P2"
}
]
})
你可以在這里查看
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/366828.html
