Welcome to OGeek Q&A 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...