使用正则表达式的Mongo聚合查询组

时间:2019-01-08 15:48:32

标签: mongodb mongodb-query aggregation-framework

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

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

是否可以合计使用正则表达式组?像这样:

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 }}
}]

或者哪种方法是最好的?我如何修改此查询以获取该时间范围内正则表达式匹配项的计数

1 个答案:

答案 0 :(得分:2)

您可以在$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 }
  }}
])
相关问题