【问题标题】:Mongo aggregate query group using regex使用正则表达式的 Mongo 聚合查询组
【发布时间】:2019-06-03 08:23:13
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您可以在$match 本身内部使用$regex,然后使用$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 }
      }}
    ])
    

    【讨论】:

    • 谢谢你的作品!有另一个查询我试图通过如下分组将数据输出到另一个集合: { "$group": {"_id": null,"count": { "$sum": 1 }},"updated_time":{ " $push": "$updated_time" }}, { "$out" : "new_Coll" }.. 但这是根据计数值添加更新时间。我只希望 update_time 在新集合中出现一次
    • 它将添加 count 和 update_time 数组,仅此而已
    • 是的,如果计数为 5,update_time 会被多次添加 updated_time 被添加 5 次。我的推送语句不正确吗?
    • 是的,它会增加 5 倍,因为文档的数量也是 5。
    • 可以只添加一次吗?
    猜你喜欢
    • 1970-01-01
    • 2014-08-11
    • 1970-01-01
    • 2015-06-21
    • 2018-01-13
    • 2012-04-30
    • 2022-01-18
    • 1970-01-01
    • 2019-05-06
    相关资源
    最近更新 更多