[英]how to use $regex search in referenced field in mongodb
我正在处理一个任务,这是我使用了两种模式
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,
}
那么,如何在此用户引用字段的“员工模式”中使用$ regex搜索first_name? 我尝试了很多方法,无法做到。 我该如何解决? 提前致谢
第一种方法:
使用$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
$match
会使查询有点慢。
第二种方法:
首先使用$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" }
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.