在 MongoDB 中使用 JS 函数和正则表达式来匹配字段

Using a JS function and regex in MongoDB to match fields

我想使用 MongoDB Shell 查找 field_1 是否与文档中 field_2 的开头匹配,并获取匹配的文档数不匹配。

field_1和field_2在同一个文档中,大约有180k文档。
field_1: 2 个字符串类型的数字(例如“10”、“40”、“15”)
field_2: 8 个字符串类型的数字 (Ex. '10102020', '40204010')

下面是我目前的代码。它returns没什么。

db.coll_1.find().forEach(
  function(x) {
    db.coll_1.find({
      field_1: {$regex: /^x.field_2*/}
    })

查询

  • group by null => 集合的所有文档作为 1 组
  • 2 个累加器
    • 如果field2的前2个字符=field1(n-match+1)
    • 如果不是field2的前2个字符=field1(n-not-match+1)

Test code here

db.collection.aggregate([
  {
    "$group": {
      "_id": null,
      "n-match": {
        "$sum": {
          "$cond": [
            {
              "$eq": [
                "$field1",
                {
                  "$substrCP": [
                    "$field2",
                    0,
                    2
                  ]
                }
              ]
            },
            1,
            0
          ]
        }
      },
      "n-not-match": {
        "$sum": {
          "$cond": [
            {
              "$ne": [
                "$field1",
                {
                  "$substrCP": [
                    "$field2",
                    0,
                    2
                  ]
                }
              ]
            },
            1,
            0
          ]
        }
      }
    }
  },
  {
    "$project": {
      "_id": 0
    }
  }
])