首页 > 解决方案 > 如何根据正则表达式值和其他几个字段对值求和?

问题描述

我有包含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 } },
  ])

标签: javascriptmongodbmongoose

解决方案


推荐阅读