Home > Back-end >  Using a JS function and regex in MongoDB to match fields
Using a JS function and regex in MongoDB to match fields

Time:09-16

I want to find if field_1 matches the beginning of field_2 within a document, using MongoDB Shell, and get the count of documents that matches and that does not match.

field_1 and field_2 are in the same document, and there are about 180k documents.
field_1: 2 numbers in string type (Ex. '10', '40', '15')
field_2: 8 numbers in string type (Ex. '10102020', '40204010')

Below is my code so far. It returns nothing.

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

CodePudding user response:

Query

  • group by null => all documents of collection as 1 group
  • 2 accumulators
    • if the first 2 characters of the field2 = field1 (n-match 1)
    • if not the first 2 characters of the field2 = 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
    }
  }
])
  • Related