我怎样才能得到特定的数组(或数组的键)?
How can i get the specific array (or key of the array)?
如何在mongoDB.
中获取包含"unique6"的特定数组(或数组的键)
注意:数组中的值是唯一的。
{
"_id" : "DETbQx7i9Sunu9w88",
"someKey" : {
"arr1" : ["unique1", "unique2", "unique3"],
"arr2" : ["unique4", "unique5", "unique6"],
"arr3" : ["unique7", "unique8", "unique9"]
}
}
借助 MongoDB,您可以使用本机 JavaScript 函数来获取所需的 BSON 属性。本质上,您可以使用 find()
and forEach()
methods, or if you have a specific document that you need to query you can use the findOne()
方法的组合迭代集合中的文档,其中 returns 单个文档。下面在Mongoshell中演示如何使用前者获取包含元素"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
});
如何在mongoDB.
中获取包含"unique6"的特定数组(或数组的键)注意:数组中的值是唯一的。
{
"_id" : "DETbQx7i9Sunu9w88",
"someKey" : {
"arr1" : ["unique1", "unique2", "unique3"],
"arr2" : ["unique4", "unique5", "unique6"],
"arr3" : ["unique7", "unique8", "unique9"]
}
}
借助 MongoDB,您可以使用本机 JavaScript 函数来获取所需的 BSON 属性。本质上,您可以使用 find()
and forEach()
methods, or if you have a specific document that you need to query you can use the findOne()
方法的组合迭代集合中的文档,其中 returns 单个文档。下面在Mongoshell中演示如何使用前者获取包含元素"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
});