Search code examples
mongodbmongovue

How to find specific key in MongoDB?


I have to find all the documents which include "p396:branchCode" as key in MongoDB.Value does not matter,can be anything.I tried using

{"p396:branchCode": new RegExp(".*")}

in MongoVUE but i found nothing. My db is very nested and branchCode has superkey "p396:checkTellersEApproveStatus"


Solution

  • Your key is nested under a super-key, so you need to use the dot-operator:

    {"p396:checkTellersEApproveStatus.p396:branchCode": {$exists: true}}
    

    This assumes p396:branchCode is always under p396:checkTellersEApproveStatus. When that's not the case, you have a problem, because MongoDB does not allow to do queries for unknown keys. When the number of possible super-keys is low, you could query for all of them with the $or-operator. When not, then your only option is to refactor your objects to arrays. To give an example, a structure like this:

    properties: {
         prop1: "value1",
         prop2: "value2",
         prop3: "value3"
    }
    

    would be far easier to query for values under arbitrary keys when made to look like this:

    properties: [
         { key: "prop1", value:"value1"} ,
         { key: "prop2", value:"value2"},
         { key: "prop3", value:"value3"}
    ]
    

    because you could just do db.collection.find({"properties.value":"value2"})