Search code examples
mongodbmongodb-queryaggregation-frameworkmongodb-indexes

How can i get the specific array (or key of the array)?


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"]      
    }
}

Solution

  • 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    
    });