【问题标题】:how to use $regex search in referenced field in mongodb如何在 mongodb 的引用字段中使用 $regex 搜索
【发布时间】:2019-05-02 06:19:36
【问题描述】:

我正在为一项任务而苦苦挣扎,我使用了两个模式

User Schema
{
  "first_name": String,
  "last_name":String,
  "address": String
}

Employee schema
{
  user:{
      type: ObjectId,
      ref: 'User'
  },
  gross_pay: String,
  net_pay: String
  tax: String,

}

那么,如何在这个用户引用的字段中使用 Employee Schema 中的 $regex 搜索 first_name?试了很多方法,都搞不定。我该如何解决?在此先感谢

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    第一种方法:

    使用$lookup 聚合

    Employee.aggregate([
      { "$lookup": {
        "from": "users",
        "let": { "user": "$user" },
        "pipeline": [
          { "$match": { "$expr": { "$eq": ["$_id", "$$user"] }}},
          { "$project": { "firstName": 1 }}
        ],
        "as": "user"
      }},
      { "$unwind": "$user" },
      { "$match": { "user.firstName": { "$regex": your_string, "$options": "i" }}}
    ])
    

    但这并不是更好的方法,因为$lookup 阶段被应用于所有Employee 文档,然后$match 应用于用户firstName 使得查询有点慢。

    第二种方法:

    首先使用$regex找到firstName等于匹配字符串的用户,然后在Employee集合中找到_id。

    const userIds = await (Users.find({ "firstName": { "$regex": your_string, "$options": "i" } })).map(user => user._id)
    
    const employees = await Employee.find({ "user": { "$in": userIds }})
    

    第三种方法:

    将user 架构的单个键firstName 保留在employee 架构中

    员工架构

      user: { type: ObjectId, ref: 'User' },
      gross_pay: String,
      net_pay: String
      tax: String
      firstName: String
    

    然后直接使用查询

    const userIds = await Employee.find({
      "firstName": { "$regex": your_string, "$options": "i" }
    })
    

    【讨论】:

      猜你喜欢
      • 2020-06-04
      • 2016-11-23
      • 1970-01-01
      • 1970-01-01
      • 2012-08-30
      • 1970-01-01
      • 2013-06-20
      • 2022-06-26
      • 2013-07-31
      相关资源
      最近更新 更多