Mongo find value with unknown parent key

徘徊边缘 提交于 2021-02-07 09:24:29

问题


I am looking for a value in a Mongo table where its parent key might not have a descriptive or known name. Here is an example of what one of our documents looks like.

    { 
       "assetsId": {
         "0": "546cf2f8585ffa451bb68369" 
      },
       "slotTypes": {
         "0": { "usage": "json" },
         "1":  { "usage": "image" }
      }
    }

I am looking to see if this contains "usage": "json" in slotTypes, but I can't guarantee that the parent key for this usage will be "0".

I tried using the following query without any luck:

db.documents.find(
   {
     slotTypes:
       {
          $elemMatch:
            {
               "usage": "json"
            }
       }
    }
)

Sorry in advance if this is a really basic question, but I'm not used to working in a nosql database.


回答1:


I'm not sure you're going to be able to solve elegantly this with your current schema; slotTypes should be an array of sub-documents, which would allow your $elemMatch query to work. Right now, it's an object with numeric-ish keys.

That is, your document schema should be something like:

{
   "assetsId": {
     "0": "546cf2f8585ffa451bb68369"
  },
   "slotTypes": [
     { "usage": "json" },
     { "usage": "image" }
  ]
}

If changing the data layout isn't an option, then you're going to need to basically scan through every document to find matches with $where. This is slow, unindexable, and awkward.

db.objects.find({$where: function() {
  for(var key in this.slotTypes) {
    if (this.slotTypes[key].usage == "json") return true;
  }
  return false;
}})

You should read the documentation on $where to make sure you understand the caveats of it, and for the love of all that is holy, sanitize your inputs to the function; this is live code that is executing in the context of your database.



来源:https://stackoverflow.com/questions/27026674/mongo-find-value-with-unknown-parent-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!