我有一个名为csgoItems的猫鼬文档和架构,如下所示:
{
"_id": {
"$oid": "56ff8fb815ad7ecdede3bc3c"
},
"csgo_number": 1,
"last_updated": 1459589048324,
"items": {
"Shadow Daggers | Urban Masked (Well-Worn)": {
"market_hash_name": "Shadow Daggers | Urban Masked (Well-Worn)",
"sale_price": 134.29
},
"Shadow Daggers | Urban Masked (Minimal Wear)": {
"market_hash_name": "Shadow Daggers | Urban Masked (Minimal Wear)",
"sale_price": 108.3
},
"Shadow Daggers | Urban Masked (Field-Tested)": {
"market_hash_name": "Shadow Daggers | Urban Masked (Field-Tested)",
"sale_price": 79.73
},
"Shadow Daggers | Urban Masked (Battle-Scarred)": {
"market_hash_name": "Shadow Daggers | Urban Masked (Battle-Scarred)",
"sale_price": 73.17
},
"Shadow Daggers | Stained (Well-Worn)": {
"market_hash_name": "Shadow Daggers | Stained (Well-Worn)",
"sale_price": 113.25
}
}
}
我正在尝试使用market_hash_names数组返回仅具有这些市场哈希名称的项目列表,如下所示
var searchItems = ["Shadow Daggers | Stained (Well-Worn)", "Shadow Daggers | Urban Masked (Battle-Scarred)"]
我已经试过了
csgoItems.find({"items": {$in: searchItems}}, function(err, found){
if(err){
console.log(err);
}else{
console.log(found);
}
如何获得这些结果?
最佳答案
该查询不起作用,因为$in
运算符仅适用于数组。
要根据散列的属性过滤查询结果,您需要使用MongoDB的mapReduce
一个简单的解决方案是:
定义一个函数将哈希映射转换为数组
function hashToArray(hash) {
return Object.keys(hash).map(function(key) {
return hash[key];
});
}
定义mapReduce查询的选项
hashToArray
函数将用于将每个文档的items
哈希转换为数组。var options = {};
options.map = function (){
emit(this._id, hashToArray(this.items), 1);
}
options.reduce = function (key, values){
return values[0];
}
执行map reduce并针对结果运行查询
csgoItems.mapReduce(options, function(err, model, stats) {
model.find({"items.market_hash_name": {$in: searchItems}}, function(err, foundItems){
// use the result
});
});
关于javascript - 查询具有属性数组的Mongoose Hash Map?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36380014/