我的檔案:
[{
"_id":"621c6e805961def3332bcf97",
"title":"monk plus",
"brand":"venture electronics",
"category":"earphones",
"variant":[
{
"price":1100,
"impedance":"16ohm"
},
{
"price":1600,
"impedance":"64ohm"
}],
"salesCount":185,
"buysCount":182,
"viewsCount":250
},
{
"_id":"621c6dab5961def3332bcf92",
"title":"nokia1",
"brand":"nokia",
"category":"mobile phones",
"variant":[
{
"price":10000,
"RAM":"4GB",
"ROM":"32GB"
},
{
"price":15000,
"RAM":"6GB",
"ROM":"64GB"
},
{
"price":20000,
"RAM":"8GB",
"ROM":"128GB"
}],
"salesCount":34,
"buysCount":21,
"viewsCount":80
}]
預期產出
[{
_id:621c6e805961def3332bcf97
title:"monk plus"
brand:"venture electronics"
category:"earphones"
salesCount:185
viewsCount:250
variant:[
{
price:1100
impedance:"16ohm"
}]
}]
我試過這種聚合方法
[{
$match: {
'variant.price': {
$gte: 0,$lte: 1100
}
}},
{
$project: {
title: 1,
brand: 1,
category: 1,
salesCount: 1,
viewsCount: 1,
variant: {
$filter: {
input: '$variant',
as: 'variant',
cond: {
$and: [
{
$gte: ['$$variant.price',0]
},
{
$lte: ['$$variant.price',1100]
}
]
}
}
}
}}]
這個方法回傳預期的輸出,現在我的問題是有沒有其他更好的方法可以回傳預期的輸出。此外,提前謝謝你,因為我是nosql資料庫的新手,所以我很想向社區學習。記下預期輸出特定檔案的所有屬性必須僅回傳我要根據價格過濾的物件的變數陣列。
uj5u.com熱心網友回復:
您的聚合管道沒有任何問題,還有其他方法可以做到這一點。如果您只想回傳匹配的檔案,只有第一個匹配的陣列元素,這是另一種方法。(.$不幸的是,該語法僅回傳第一個匹配項。)
db.collection.find({
// matching conditions
"variant.price": {
"$gte": 0,
"$lte": 1100
}
},
{
title: 1,
brand: 1,
category: 1,
salesCount: 1,
viewsCount: 1,
// only return first array element that matched
"variant.$": 1
})
在mongoplayground.net上試試。
或者,如果您想使用聚合管道并完整回傳所有匹配的檔案(過濾后的陣列除外),您可以使用您想要使用的元素"$set"(或其別名"$addFields")“覆寫”陣列。這樣做意味著你不需要"$project"任何東西。
db.collection.aggregate([
{
"$match": {
"variant.price": {
"$gte": 0,
"$lte": 1100
}
}
},
{
"$set": {
"variant": {
"$filter": {
"input": "$variant",
"as": "variant",
"cond": {
"$and": [
{ "$gte": [ "$$variant.price", 0 ] },
{ "$lte": [ "$$variant.price", 1100 ] }
]
}
}
}
}
}
])
在mongoplayground.net上試試。
uj5u.com熱心網友回復:
您的解決方案很好,只需確保在應用此步驟之前應用您的 $match 和分頁以獲得更快的查詢
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/435822.html
