javascript - 如何根据正则表达式值和其他几个字段对值求和?
问题描述
我有包含text
字段和其他几个数组类型字段的架构。
const MySchema = new Schema({
user: {
type: String,
},
text: {
type: String,
},
firstArrayField: {
type: Array,
},
secondArrayField: {
type: Array,
},
});
以前我只需要根据一个字段对值求和
My.aggregate([
{
$match: {
userId,
secondArrayField: secondArrayField || { $exists: true },
},
{
$unwind: '$firstArrayField',
},
{
$group: {
_id: secondArrayField ? {
firstArrayField: '$firstArrayField',
secondArrayField: '$secondArrayField',
} : { firstArrayField: '$firstArrayField' },
sum: { $sum: 1 },
},
},
{
$project: {
_id: 0,
firstArrayField: '$_id.firstArrayField',
sum: '$sum',
}
},
{ $sort: { sum: -1, hashtag: 1 } },
])
它运作良好。但现在我还需要基于文本字段和正则表达式搜索求和:
const query = { user };
if (secondArrayField) filter.secondArrayField = secondArrayField;
if (text) filter.text = { "$regex": text, "$options": "i" };
My.aggregate([
{
$match: query // here I changed match object
},
{
$unwind: '$firstArrayField',
},
{
$group: {
_id: secondArrayField ? {
firstArrayField: '$firstArrayField',
secondArrayField: '$secondArrayField',
text: '$text', // Here I have problem how to pass also regex
} : { firstArrayField: '$firstArrayField' }, // Here also I need to handle if neither secondArrayField nor text passed
sum: { $sum: 1 },
},
},
{
$project: {
_id: 0,
firstArrayField: '$_id.firstArrayField',
sum: '$sum',
}
},
{ $sort: { sum: -1, hashtag: 1 } },
])
解决方案
推荐阅读
- android - 获取当前在前台和后台运行的应用程序列表
- javascript - Netlify、socket.io 和 Node.js 不合作
- c++ - UDP 多播错误未收到消息
- java - Jmeter线程组持续时间
- snowflake-cloud-data-platform - 批量雪花合并查询
- jquery - 在 for 循环中将 .on('click') 分别分配给每个数组元素
- css - 在 React Native 中使用 Styled Components 为子项设置样式
- android - 时间选择器微调器未在 android 的大写字母中显示 am pm
- qml - 我如何从 qml 中的 gridview 访问 currentIndex 并在更改时更新它 [In QML]
- python - 在 Python 中读取 Windows 文件属性