Home > Back-end >  Querying keys in a docs on mongoDB by prefix
Querying keys in a docs on mongoDB by prefix

Time:02-09

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.

CodePudding user response:

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

  •  Tags:  
  • Related