node.js - 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");
- 如何对“电子邮件”应用过滤器,以便填充具有给定“电子邮件”的特定孩子?
- 如何对孩子的“姓名”应用文本搜索?
解决方案
您必须使用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
}
}
}
]);
在这里,我们首先填充仅child
指定email_id
使用$lookup
然后,我们使用正则表达式过滤child
基于搜索关键字(我使用不区分大小写)
现在,这将为您提供所有具有各自父母的孩子的列表,例如[{parent_field_1:parent_value_1,......, child:{child_object}}]
如果您想要同一父母的所有孩子,您可以$group
在后续投影中使用
推荐阅读
- css - 覆盖 React 引导组件样式
- botframework - Azure表服务retrieveEntity“跳过”函数
- html - 如何使位置绝对和相对网站,响应式
- html - 更改屏幕宽度时,Chrome 开发者工具会截断页面
- python - 使用corner.corner隐藏角图中的样本点
- javascript - 如何在反应图中更改条形图中条形的宽度?
- bash - 为什么替换时sed有时会截断?
- c++ - 如何用freeglut画一个菱形?
- generics - 尝试编写一个通用函数,该函数接受并使用 IntoIterator 作为参数
- c++ - 如何在 C++ 中使用 win32 在 Windows 上的远程计算机上创建一个新文件?