Node.js - 如何在MongoDB中对填充的字段应用过滤器和文本搜索?


const parentSchema = new Schema({
name: {
type: String,
required: true
},
childId: {
type: Schema.Types.ObjectId,
ref: "Child"
}
});
const childSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
}
});
const results = await Parent.find().populate("clientId", "email, name");
如何在"电子邮件
  1. "上应用过滤器,以便填充具有给定"电子邮件"的特定子项?
  2. 如何对孩子的"名字"进行文本搜索?

您必须使用aggregate来实现此目的,请参阅下面的代码

Parent.aggregate([
{
$lookup: {
from: 'child',
let: {
email_: "abc@example.com",
childId_: '$childId'
},
pipeline: [
{
$match: {
$expr: {
$and: [
{
$eq: ['$email', '$$email_']
},
{
$eq: ['$_id', '$$childId_']
}
]
}
}
}
],
as: 'child'
}
},{
$unwind:'$child'
},{
$match:{
'child.name':{
$regex: "SearchKeyWord",
$options: 'i' // For case insensitive search
}
}
}
]);

在这里,我们首先使用$lookup指定email_id仅填充child

然后,我们使用正则表达式根据搜索关键字过滤child(我使用了不区分大小写(

现在,这将为您提供所有孩子与各自父母的列表,例如[{parent_field_1:parent_value_1,......, child:{child_object}}]

如果你想让所有孩子都是同一父母的孩子,你可以在后续的投影中使用$group

相关内容

最新更新