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

152
Views
Querying keys in a docs on mongoDB by prefix

At the moment, i have this data in mongo

{
   "_id" : ObjectId("62021f4cbd7796d438622245"),
    "id" : "MyData",
    "Mode" : "txtx",
    "MinCost" : "0.2",
    "R:1" : "info1",
    "R:13" : "info2",
    "R:3" : "info3",
    "R:4 : "info4",
    "R:5" : "info5",
    "Cost" : "100"
}

I want to return back just the keys from this data that has prefix, for example, "R" or "R:1". Basically, want to return just the keys that matches a prefix that i'm giving.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

  • $expr
  • $gte
  • $size
  • $filter
  • $replaceRoot
  • $arrayToObject
  • $objectToArray
  • $regexFind
db.collection.aggregate([
  {
    "$match": {
      $expr: {
        "$gte": [
          {
            $size: {
              "$filter": {
                "input": { "$objectToArray": "$$ROOT"},
                "as": "s",
                "cond": { "$regexFind": { "input": "$$s.k", "regex": "R:1" } }
              }
            }
          },
          1
        ]
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$arrayToObject": {
          "$filter": {
            "input": { "$objectToArray": "$$ROOT" },
            "as": "s",
            "cond": { "$regexFind": { "input": "$$s.k", "regex": "R:1" } }
          }
        }
      }
    }
  }
])

mongoplayground

over 4 years ago · Santiago Trujillo 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!