2 回答

TA貢獻1836條經驗 獲得超13個贊
可以使用聚合管道實現此目的,$filter
$match,以便您只考慮至少具有一種匹配成分的食譜
$addFields使用$filter創建字段,以消除從中查詢的成分數組
OtherIngredient
Ingredients
$match只選擇沒有其他不良成分的食譜
$project刪除臨時字段
[
{$match: {Ingredients: {
$in: ["Eggs","Milk","Butter"]
}}},
{ $addFields: {
OtherIngredient: {
$filter: {
input: "$Ingredients",
cond: {$not: {$in: [
"$$this",
["Eggs","Milk","Butter"]
]}}
}
}
}},
{$match: {"OtherIngredient": []}},
{$project: {OtherIngredient: 0}}
])

TA貢獻1833條經驗 獲得超4個贊
對不起,我不知道Golang,但這是你需要的(是新的MongoDB 4.4):$function
let filter = ["Eggs", "Milk", "Butter"];
db.recipes.find({
$expr: {
$function: {
body: function(ingredients, filter) {
for (let i = 0; i < ingredients.length; i++) {
if (filter.indexOf(ingredients[i]) < 0) return false;
}
return true
},
args: ["$Ingredients", filter],
lang: "js"
}
}
});
- 2 回答
- 0 關注
- 132 瀏覽
添加回答
舉報