mongo 查询中的主机匹配列表不起作用

问题描述 投票:0回答:1

我有以下疑问:

mydb.my-collection.aggregate([
  {
    $match: {
    
      $and: [
        {timestamp:
        {
            $gte: $__timeFrom,
            $lte: $__timeTo
        }}       
      ]
    }
  },
  {
    $group: {
      _id: {
        host: "$host"
      },
      sum: {$sum: "$status"},
      count: {$count: {}}
    }
  },
  {
    $project: {
      price: {$divide: ["$sum", "$count"]}
    }
  }
])

我试图仅匹配特定主机,因此我更新了查询,如下所示:

   mydb.my-collection.aggregate([
      {
        $match: {
            host : {$regex: ".*SER1.*"},
            host:  {$regex: ".*SER2.*"},
            host: {$regex: ".*SER3.*"}
          $and: [
            {timestamp:
            {
                $gte: $__timeFrom,
                $lte: $__timeTo
            }}       
          ]
        }
      },
      {
        $group: {
          _id: {
            host: "$host"
          },
          sum: {$sum: "$status"},
          count: {$count: {}}
        }
      },
      {
        $project: {
          price: {$divide: ["$sum", "$count"]}
        }
      }
    ])

我还尝试了

{host: { $in:["SER1","SER2","SER3"] }}
来匹配主机。 但我的结果显示了所有其他主机,我只想显示 SER1、SER2、SER3。

有什么方法可以使用我想要匹配的值列表或数组吗?

regex mongodb collections mongodb-query mongodb-compass
1个回答
0
投票

对象中不能有相同的字段名称。

您应该与

$expr
一起使用才能使用
$regexMatch
运算符。要匹配任何正则表达式模式,您应该将多个(正则表达式)条件包装在
$or
运算符中。

此外,您需要修改用于比较

timestamp
字段的查询,以应用
$expr

{
    $match: {
      $expr: {
        $and: [
          {
            $or: [
              {
                $eq: [
                  {
                    $regexMatch: {
                      input: "$host",
                      regex: ".*SER1.*"
                    }
                  },
                  true
                ]
              },
              {
                $eq: [
                  {
                    $regexMatch: {
                      input: "$host",
                      regex: ".*SER2.*"
                    }
                  },
                  true
                ]
              },
              {
                $eq: [
                  {
                    $regexMatch: {
                      input: "$host",
                      regex: ".*SER3.*"
                    }
                  },
                  true
                ]
              }
            ]
          },
          {
            $and: [
              {
                $gte: [
                  "$timestamp",
                  __timeFrom
                ]
              },
              {
                $lte: [
                  "$timestamp",
                  __timeTo
                ]
              }
            ]
          }
        ]
      }
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.