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

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

nosql - MongoDB find by object key

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...