Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following structure (swagger file):

{
    "swagger":"2.0",
    ...
    "paths": {
        "/pet": {
            "post" : { ... }
            "put" : { ... }
         },
         "/anotherpetstore": {
            "post" : { ... }
            "put" : { ... }
         }
    }
}

I now want to have something like {'paths': {'$regex':'pet'}} and find both paths.

Is that even possible in MongoDB?

I found some similar questions which never looked for the name of the object itself.
MongoDB Search nested Objects without knowing Key
How to find specific nested objects without knowing the parent key in mongodb

question from:https://stackoverflow.com/questions/65625787/mongodb-find-by-object-key

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

If I've understand you correctly, you can do something like this:

  • Convert object paths into an array to can get the key value using $objectToArray.
  • Then filter by regex expression the key you want. In this case pet is to match values where string has "pet" but you can use another regex if you want.
  • After that, we will have only routes objects that matches the regex, then again convert to object using $arrayToObject
db.collection.aggregate([
  {"$match": {"swagger": "2.0"}},
  {"$set": {"paths": {"$objectToArray": "$paths"}}},
  {
    "$set": {
      "paths": {
        "$filter": {
          "input": "$paths",
          "as": "p",
          "cond": {"$regexMatch": {"input": "$$p.k","regex": "pet"}}
        }
      }
    }
  },
  {"$set": {"paths": {"$arrayToObject": "$paths"}}}
])

Example here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...