简体   繁体   English

猫鼬-通过部分匹配另一个数组来基于对象数组字段查找文档

[英]Mongoose - find documents based on array of objects field by partial matching another array

So, I`ll send to my api the following array format 因此,我将以下数组格式发送给我的api

['apple', 'orange', 'mango', 'kiwi', 'lemon']

In my database, I have a collection called Recipes having the following field format 在我的数据库中,我有一个名为“ Recipes的集合,具有以下字段格式

ingredients: [ { .., name: 'apple', .. }, { .., name: 'orange', .. }] - being an array of objects with this kind of format ingredients: [ { .., name: 'apple', .. }, { .., name: 'orange', .. }] -是具有这种格式的对象数组

Having the following documents in my DB: 我的数据库中包含以下文档:

Document #1 文件#1

ingredients:[ {.., name: 'apple', ..}, {.., name: 'kiwi', ..}, {.., name: 'banana', ..}]

Document #2 文件#2

ingredients:[ {.., name: 'apple', ..}, {.., name: 'orange', ..}, {.., name: 'kiwi', ..}]

Document #3 文件#3

ingredients:[ {.., name: 'lemon', ..}, {.., name: 'tomato', ..}, {.., name: 'potato', ..}]

How the mongoose query should look like to return Document#2, Document#1, Document#3(this order as their arrays are the most similar to initial requested array) 猫鼬查询应如何返回Document#2,Document#1,Document#3(此顺序是因为它们的数组与初始请求的数组最相似)

You can use below aggregation: 您可以使用以下聚合:

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
        }
    }
])

All you need is to add additional field which counts all matching ingredients (using $setIntersection ) and then sort by that field in descending order. 您只需要添加其他字段即可计算所有匹配成分(使用$ setIntersection ),然后按该字段降序排序。 Since your ingredients contains objects you can use $map to retrieve only names. 由于成分中包含对象,因此可以使用$ map仅检索名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM