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

180
Views
How to get all keys of collection that contains certain(String) value in mongodb

Suppose I have a collection i.e. A.

I want to get all the keys to this collection that have particular value i.e. "hello"

   {
      "a": "its me hello",
      "b": "it does not have value",
      "c": "It has hello"
   }

In that case, I want to query to return a and c keys. Which contains the string "hello".

Is there any way to do that?

Or any way to do that in spring boot?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can do this by reshaping the data in the datasource using objectToArray

Play

db.collection.aggregate([
  {
    "$project": {
      "data": {
        "$objectToArray": "$$ROOT"
      }
    }
  },
  {
    $unwind: "$data"
  },
  {
    "$match": {
      "data.v": {
        $regex: "hello"
      }
    }
  }
])

Another advanced version here It reshapes the data back

db.collection.aggregate([
  {
    "$project": {
      "data": {
        "$objectToArray": "$$ROOT"
      }
    }
  },
  {
    $unwind: "$data"
  },
  {
    "$match": {
      "data.v": {
        $regex: "hello"
      }
    }
  },
  {
    $group: {//Grouping back and restructuring the data so that objectToArray will bring the original format easily.
      "_id": "$_id",
      data: {
        "$addToSet": {
          k: "$data.k",
          v: "$data.v"
        }
      }
    }
  },
  {
    "$project": {
      "data": {
        "$arrayToObject": "$data"
      }
    }
  }
])

Refere the documentation of arrayToObject and objectToArray, then $regex

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!