how to use $regex search in referenced field in mongodb

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 15:34:49

问题


i am struggling with a task, which it is I used two schemas

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,

}

Well, how can I search first_name using $regex in Employee Schema in this user referenced field? I tried in so many ways, can't get it. how can i resolve it? Thanks in advance


回答1:


First Approach:

Using $lookup aggregation

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

But it is not the better approach as the $lookup stage is being applied to all the Employee documents and then $match to the users firstName makes the query bit slow.

Second Approach:

First find the users having firstName equal to the match string using $regex and then find the _id in the Employee collection.

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

const employees = await Employee.find({ "user": { "$in": userIds }})

Third Approach:

Keep the single key firstName of the user schema in the employee schema

Employee schema

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

and then use query directly

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


来源:https://stackoverflow.com/questions/53551680/how-to-use-regex-search-in-referenced-field-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!