【问题标题】:Given a mongodb model's array I want to find records in which that array has the most matches using mongoose给定一个 mongodb 模型的数组,我想使用 mongoose 查找该数组匹配最多的记录
【发布时间】:2021-12-28 14:31:07
【问题描述】:

我有一个这样的猫鼬模式:

const userSchema = new mongoose.Schema({
  keywords: [{ "type": String, "enum": ["yup", "nope"] }],
})

在这里,我有一个用户有一组关键字,我想在我的数据库中找到与这个特定用户的关键字集最相似的记录。

例如,如果用户将["yup" "nope"] 作为关键字,我想查找关键字数组中包含“yup”或“nope”或两者兼有的用户的所有记录。这只是一个示例,实际上,用户将有更多的关键字可供选择。

如何使用猫鼬做到这一点?

我正在考虑对数组中的值进行一次热编码,并且可以将具有最匹配 1 的记录添加到另一个表“最相似值表或其他东西”中,该表为每个用户维护此列表,用户为外键。但我还没有为此想出一个有效和/或有效的算法。

【问题讨论】:

    标签: node.js database mongodb express mongoose


    【解决方案1】:

    在我看来,最好的方法是正则表达式。我给你写了一个示例函数,如何使用 mongoose 在 MongoDB 中搜索和过滤数据。例如,让我们按姓氏搜索客户,例如开始、结束、包含字符串“yup”。请注意,使用正则表达式搜索是区分大小写的默认设置。如果在正则表达式后添加“i”,它将不区分大小写。

    async function getCustomers() {
     const customers = await Customer
      //case search lastName whitch starts with "yup" - case sensitive
     .find({lastName: /^yup/})
     //or case search lastName whitch ends with "yup" - case insensitive
     .find({lastName: /yup$/i })
     //or case search lastName whitch contains "yup" in any part 
     .find({lastName: /.*yup.*/ })
     .limit(20) //get top 20 results
     .sort({lastName: 1}) // sort by lastName
    console.log(customers)}
    
    
    
     //searching in array
     const customerList = ['Smith', 'Jackson'];
    
      async function getCustomers(arr) {
       return await Customer
       .find({lastName: {$in: arr}})
       .limit(20) //get top 20 results
       .sort({lastName: 1}) // sort by lastName
       }
      
       getCustomers(customerList);
    

    更多信息请查看文档: https://docs.mongodb.com/manual/reference/operator/query/regex/

    【讨论】:

    • 谢谢,这似乎是一个很好的方法。一旦我尝试过,我一定会告诉你的。
    • 非常感谢您的方法完美运行,现在我只需要找出在数组中查找多个字符串而不是一个字符串的正则表达式,这样我就可以匹配多个值并找到具有大多数匹配。
    • 你可以使用 in 运算符:.....find({lastName: {$in: ['Smith', Jackson,] }}) 你也可以使用 and, or, not in and其他比较运算符。
    • 我添加了如何使用数组查询的示例。
    • 非常感谢您的解决方案正在按照我想要的方式完美运行。真的很感激。
    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 2019-08-17
    • 2017-06-15
    • 1970-01-01
    • 2020-03-15
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多