0

我有两个集合:PriceShop(ShopId, Price, DrugId), Drug(DrugId, MaxPrice, MinPrice)。

我使用 map/reduce 在 PriceShop Collection 中查找同一药物的 maxPrice、minPrice,然后使用 map/reduce 结果更新 Drug collection。

但是在 MongoDb 2.4 中,我不能再在 map 或 reduce 函数中使用“db.Drug.Update”,那么有没有其他解决方案可以做到这一点。这是我的地图/减少代码: db.PriceShop.MapReduce(map, reduce);

function Map() {
emit(this.Drugid, {
    "count" : 0.5,
    "maxprice" : this.Price,
    "minprice" : this.Price,
    "stateid" : this.State
});
emit(this.Drugid, {
    "count" : 0.5,
    "maxprice" : this.Price,
    "minprice" : this.Price,
    "stateid" : this.State
});
}

function Reduce(key, arr_values) {
var count = 0;
var maxprice = 0;
var minprice = 0;
var drugItem = db.drug.findOne({
        "_id" : key
    });
arr_values.forEach(function (item) {
    if (item["stateid"] == 0) {
        count += item["count"];
        if (item["maxprice"] > maxprice && item["maxprice"] > 0) {
            maxprice = item["maxprice"];
        }
        if (minprice == 0) {
            minprice = item["minprice"];
        } else if (item["minprice"] > 0 && item["minprice"] < minprice) {
            minprice = item["minprice"];
        }
    }

});
var MaxStorePrice = 0;
var MinStorePrice = 0;
var PriceShopCount = 0;
if (drugItem != null && drugItem["MaxStorePrice"] != null) {
    MaxStorePrice = drugItem["MaxStorePrice"];
}
if (drugItem != null && drugItem["MinStorePrice"] != null) {
    MinStorePrice = drugItem["MinStorePrice"];
}
if (drugItem != null && drugItem["PriceShopCount"] != null) {
    PriceShopCount = drugItem["PriceShopCount"];
}
if (MaxStorePrice != maxprice || MinStorePrice != minprice || PriceShopCount != count) {
    db.drug.update({
        "_id" : key
    }, {
        "$set" : {
            "MaxStorePrice" : maxprice,
            "MinStorePrice" : minprice,
            "PriceShopCount" : NumberInt(count)
        }
    });
}
return {
    "count" : count,
    "maxprice" : maxprice,
    "minprice" : minprice,
    "MaxStorePrice" : MaxStorePrice,
    "MinStorePrice" : MinStorePrice,
    "PriceShopCount" : PriceShopCount
};

}

4

0 回答 0