2
我使用node-mongodb-native
來實現MongoDB查詢功能。我需要執行一個查詢,如果tag
相匹配的部分或組合firstName
和lastName
這樣的:node.js - mongodb native中的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' } }
];
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將在組合字符串上應用模式,結果是一個空數組。我感到很困惑