我正在使用 node-mongodb-native
来实现 MongoDB 查询功能。如果 tag
匹配一个部分或组合 firstName
和 lastName
,我需要执行查询,如下所示:
filter50WithTagSkip(tag, skip) {
return new Promise((resolve, reject) => {
const regex = new RegExp(tag, 'g');
const or_criteria = [
{ firstName: { $regex: regex, $options: 'i' } },
{ lastName: { $regex: regex, $options: 'i' } },
{ fullName: { $regex: regex, $options: 'i' } },
{ email: { $regex: regex, $options: 'i' } },
{ phone: { $regex: regex, $options: 'i' } }
];
this._db.collection(this._table)
.aggregate({
$project: {
deleted: 1,
firstName: 1,
lastName: 1,
email: 1,
phone: 1,
fullName: { $concat: ['$firstName', ' ', '$lastName'] }
}
}).match({
$or: or_criteria,
deleted: false
})
.skip(skip)
.limit(50)
.toArray((err, res) => {
if (err) {
this._logger.error(err);
reject(err);
} else {
resolve(res);
}
});
});
}
使用这些示例:
{
firstName: "first1",
lastName: "last1"
},
{
firstName: "first2",
lastName: "last2"
}
如果 tag
是 first
,则结果包含两个文档。但是,如果我注释掉 firstName
和 lastName
标准,认为不需要它们,因为 RegExp 将在组合字符串上应用模式,结果是一个空数组。我感到很困惑
最佳答案
我想我自己找到了解决方案,这是通过这个库初始化聚合查询的正确方法:
filter50WithTagSkip(tag, skip) {
return new Promise((resolve, reject) => {
const regex = new RegExp(tag, 'g');
const or_criteria = [
// { firstName: { $regex: regex, $options: 'i' } },
// { lastName: { $regex: regex, $options: 'i' } },
{ fullName: { $regex: regex, $options: 'i' } },
{ email: { $regex: regex, $options: 'i' } },
{ phone: { $regex: regex, $options: 'i' } }
];
const project_criteria = {
deleted: 1,
// firstName: 1,
// lastName: 1,
email: 1,
phone: 1,
fullName: { $concat: ['$firstName', ' ', '$lastName'] }
};
const match_criteria = {
$or: or_criteria,
deleted: false
};
const aggregate_criteria = [{ $project: project_criteria }, { $match: match_criteria }];
this._db.collection(this._table)
.aggregate(aggregate_criteria)
.skip(skip)
.limit(50)
.toArray((err, res) => {
if (err) {
this._logger.error(err);
reject(err);
} else {
resolve(res);
}
});
});
}
关于javascript - node.js - MongoDB native 中的 RegExp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46581011/