Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

231
Views
Using a JS function and regex in MongoDB to match fields

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*/}
    })
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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
    }
  }
])
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!