0

How can i get the specific array (or key of the array) which contain "unique6" in mongoDB.

Note: value inside array is unique.

{
    "_id" : "DETbQx7i9Sunu9w88",
    "someKey" : {
           "arr1" : ["unique1", "unique2", "unique3"],
           "arr2" : ["unique4", "unique5", "unique6"],
           "arr3" : ["unique7", "unique8", "unique9"]      
    }
}
iamhimadri
  • 532
  • 1
  • 5
  • 20
  • Your question is a bit unclear here, help me to understand it correctly. Do you mean you would want to get the array which contains the element `"unique6"`, i.e. the array `arr2`, is that correct? – chridam Apr 10 '15 at 08:18

1 Answers1

0

With MongoDB you can use native JavaScript functions to get the desired BSON attributes. Essentially you could iterate over the documents in your collection using a combination of the find() and forEach() methods, or if you have a specific document that you need to query you can use the findOne() method which returns a single document. The following demonstrates in Mongo shell how to get the array key which contains the element "unique6" using the former:

db.collection.find().forEach(function (doc){
    var arrayKey = "",
        obj = doc["someKey"];
    for (var key in obj) {        
        obj[key].forEach(function(e) {
            if (e == "unique6") arrayKey = key
        });
    }
    print(arrayKey); // <-- this variable has the array key    
});
chridam
  • 100,957
  • 23
  • 236
  • 235