首页 > 解决方案 > 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?

标签: mongodbspring-bootmongodb-query

解决方案


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


推荐阅读