[英]Mongoose: Find all documents with array field which is included in another array
[英]Mongoose - find documents based on array of objects field by partial matching another array
因此,我將以下數組格式發送給我的api
['apple', 'orange', 'mango', 'kiwi', 'lemon']
在我的數據庫中,我有一個名為“ Recipes
的集合,具有以下字段格式
ingredients: [ { .., name: 'apple', .. }, { .., name: 'orange', .. }]
-是具有這種格式的對象數組
我的數據庫中包含以下文檔:
文件#1
ingredients:[ {.., name: 'apple', ..}, {.., name: 'kiwi', ..}, {.., name: 'banana', ..}]
文件#2
ingredients:[ {.., name: 'apple', ..}, {.., name: 'orange', ..}, {.., name: 'kiwi', ..}]
文件#3
ingredients:[ {.., name: 'lemon', ..}, {.., name: 'tomato', ..}, {.., name: 'potato', ..}]
貓鼬查詢應如何返回Document#2,Document#1,Document#3(此順序是因為它們的數組與初始請求的數組最相似)
您可以使用以下聚合:
db.collection.aggregate([
{
$addFields: {
totalMatch: {
$size: {
$setIntersection: [['apple', 'orange', 'mango', 'kiwi', 'lemon'], { $map: { input: "$ingredients", as: "ingredient", in: "$$ingredient.name" } }]
}
}
}
},
{
$sort: {
totalMatch: -1
}
},
{
$project: {
totalMatch: 0
}
}
])
您只需要添加其他字段即可計算所有匹配成分(使用$ setIntersection ),然后按該字段降序排序。 由於成分中包含對象,因此可以使用$ map僅檢索名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.