Brian
Brian

Reputation: 61

Mongo find value with unknown parent key

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.

Upvotes: 2

Views: 2460

Answers (1)

Chris Heald
Chris Heald

Reputation: 62688

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.

Upvotes: 5

Related Questions