我正在創建一個專案,我在其中使用 mongoDB,并且我想查詢一些食譜。
我的資料庫中的食譜檔案示例 我想獲取其中“成分”陣列(句子)的食譜,其中任何單詞都匹配另一個陣列(單個單詞)。
我想出了這樣的事情:
const recipes = await recipe
.aggregate([
// add a weight parameter based of number of ingredients matching searched ingredient
{
$project: {
name: 1,
ingredients: 1,
tags: 1,
url: 1,
weight: {
$add: [
{
$size: {
$setIntersection: ["$ingredients", ingrArr],
},
},
],
},
},
},
{ $sort: { weight: -1 } },
])
它顯示了食譜,其中有確切的字串,如“面粉”,我添加了“重量”以根據匹配詞的數量對它們進行排序,但它不會顯示類似:“一杯面粉”的內容。
我嘗試了 $unwind,但我無法讓它作業。有人可以幫助我嗎?
uj5u.com熱心網友回復:
檔案
{
name: "A Simple Seafood Bisque",
ingredients: [
"1 (12 ounce) can evaporated milk",
"1/2 cup half-and-half",
"1/2 cup dry white wine",
"1 roasted red pepper, chopped",
"2 teaspoons butter",
"1 bay leaf",
"1 pinch salt",
"1 dash hot pepper sauce (such as Tabasco's)",
"2 (8 ounce) cans oysters, drained and rinsed",
"2 (6.5 ounce) cans chopped clams with juice",
"1 cup chopped portobello mushrooms",
"2 green onions, minced"
],
url: "http://allrecipes.com/recipe/77790/a-simple-seafood-bisque/"
}
詢問
const key = 'pepper'
db.collection.aggregate(
{
$match: {}
},
{
$addFields: {
weight: {
$size: {
$filter: {
input: '$ingredients',
as: 'element',
cond: {
$regexMatch: { input: '$$element', regex: RegExp(key) }
}
}
}
}
}
}
)
結果添加了一個帶有匹配元素數量的欄位權重
"weight" : 2
或更簡單的使用方法,$text并$search在成分欄位和查詢中創建文本索引
db.collection.find(
{ $text: { $search: "pepper" } },{ score: { $meta: "textScore" } }
)
結果添加了搜索的歸檔分數
"score" : 1.1833333333333333
uj5u.com熱心網友回復:
我必須添加正則運算式陣列并將其包含在查詢中。這恰好像我想要的那樣作業。謝謝
let findString = "";
ingrArr.forEach((e, index) => {
index !== ingrArr.length - 1 ? (findString = e "|") : (findString = e);
});
console.log(findString);
const recipes = await recipe
.aggregate([
// add a weight parameter based of number of ingredients matching searched
ingredient
{
$addFields: {
weight: {
$size: {
$filter: {
input: "$ingredients",
as: "element",
cond: {
$regexMatch: {
input: "$$element",
regex: RegExp(`${findString}`),
},
},
},
},
},
},
},
{ $sort: { weight: -1 } },
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/494685.html
上一篇:“non_field_errors”:[“無效資料。期望字典,但得到了QuerySet。”]來自djongo的序列化程式或模型的問題
下一篇:Mongo聚合$lookup
