首页 > 解决方案 > 使用正则表达式的 Mongo 聚合查询组

问题描述

我正在尝试编写一个脚本并从年份和特定月份添加的集合中获取数据。

并获取“名称”字段与我给定的正则表达式匹配的记录。

是否可以聚合使用正则表达式组?像这样的东西:

collection1.aggregate([
     {"$match": {"$expr":{"$and":[{"$eq":[{"$year":"$updated_time"}, year]}, {"$eq":[{"$month":"$updated_time"}, month]}]}}},
{$group : {_id : {"Name": {"$regex": '^ABC', "$options": "i"} },count: { $sum: 1 }}
}]

或者哪个是获得它的最佳方式?如何修改此查询以获取该时间范围内的正则表达式匹配计数

标签: mongodbmongodb-queryaggregation-framework

解决方案


您可以$regex$match自身内部使用,然后用于$count获取匹配文档的数量

collection1.aggregate([
  { "$match": {
    "$expr": {
      "$and": [
        { "$eq": [{ "$year": "$updated_time" }, year] },
        { "$eq": [{ "$month": "$updated_time" }, month] }
      ]
    },
    "Name": { "$regex": "^ABC", "$options": "i" }
  }},
  { "$count": "count" }
])

或者也$group可以

collection1.aggregate([
  { "$match": {
    "$expr": {
      "$and": [
        { "$eq": [{ "$year": "$updated_time" }, year] },
        { "$eq": [{ "$month": "$updated_time" }, month] }
      ]
    },
    "Name": { "$regex": "^ABC", "$options": "i" }
  }},
  { "$group": {
    "_id": null,
    "count": { "$sum": 1 }
  }}
])

推荐阅读