0

当where子句包含 select 语句时,我如何将 sql 查询转换为 mongodb map reduce ?

例如

select
    sum(l_extendedprice) / 7.0 as avg_yearly
from 
    lineitem, 
    part
where 
    p_partkey = l_partkey
    and p_brand = 'Brand#23'
    and p_container = 'MED BOX'
    and l_quantity < (
        select
            0.2 * avg(l_quantity)
        from 
            lineitem
        where 
            l_partkey = p_partkey
    );

我试过这个mapreduce,但似乎没有用。

db.runCommand({
    mapreduce: "lineitem",
    query: {
        "partsupp.ps_partkey.p_brand": "Brand#23",
        "partsupp.ps_partkey.p_container": "MED BOX"
    },
    map: function() {
        var data = {l_extendedprice: 0, l_quantity:0, total_l_quantity: 0 };

        data.l_extendedprice = this.l_extendedprice;
        data.l_quantity = this.l_quantity;
        data.total_l_quantity = 1;

        emit("avg_yearly", data);
    },
    reduce: function(key, values) {
        var data = {l_extendedprice: 0, l_quantity:0, total_l_quantity: 0 };
        var sum_l_quantity = 0;

                /*sum the l_quantity and total_l_quantity*/
        for (var i = 0; i < values.length; i++) {
            sum_l_quantity += values[i].l_quantity;
            data.total_l_quantity += values[i].total_l_quantity;
        }

                /*calculate the average l_quantity and multiply*/
        var avg_l_quantity = 0.2 * (sum_l_quantity / data.total_l_quantity);

                /*sum l_extendedprice and divide */     
        for (var i = 0; i < values.length; i++) {
            if( values[i].l_quantity < avg_l_quantity ) {
                data.l_extendedprice += values[i].l_extendedprice;
            }
        }
        data.l_extendedprice = data.l_extendedprice / 7.0;

        return data;
    },
    out: 'query017'
});

有另一种方法吗?是否可以在mapreduce的查询子句中做到这一点?或者我只是在我的代码中弄错了?

架构

{
    "_id" : ObjectId("511b7d1b3daee1b1446ecdfe"),
    "l_quantity" : 17,
    "l_extendedprice" : 21168.23,
    "l_discount" : 0.04,
    "l_shipdate" : ISODate("1996-03-13T03:00:00Z"),
    "l_commitdate" : ISODate("1996-02-12T03:00:00Z"),
    "l_receiptdate" : ISODate("1996-03-22T03:00:00Z"),
    "l_shipmode" : "TRUCK",
    "l_comment" : "blithely regular ideas caj",
    "partsupp" : {
            "ps_availqty" : 6157,
            "ps_supplycost" : 719.17,
            "ps_partkey" : {
                    "p_partkey" : NumberLong(155190),
                    "p_name" : "slate lavender tan lime lawn",
                    "p_mfgr" : "Manufacturer#4",
                    "p_brand" : "Brand#44",
                    "p_type" : "PROMO BRUSHED NICKEL",
                    "p_size" : 9,
                    "p_container" : "JUMBO JAR",
                    "p_retailprice" : 1245.19,
                    "p_comment" : "regular, final dol"
            }
    }
}
4

0 回答 0