0

如何在 mongoDB 中获取包含“unique6”的特定数组(或数组的键)。

注意:数组中的值是唯一的。

{
    "_id" : "DETbQx7i9Sunu9w88",
    "someKey" : {
           "arr1" : ["unique1", "unique2", "unique3"],
           "arr2" : ["unique4", "unique5", "unique6"],
           "arr3" : ["unique7", "unique8", "unique9"]      
    }
}
4

1 回答 1

0

使用 MongoDB,您可以使用本机 JavaScript 函数来获取所需的 BSON 属性。find()本质上,您可以使用和方法的组合来迭代集合中的文档forEach(),或者如果您有需要查询的特定文档,您可以使用findOne()返回单个文档的方法。下面演示了如何在 Mongo shell 中"unique6"使用前者获取包含元素的数组键:

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    
});
于 2015-04-10T09:07:10.403 回答