MongoDB加入/更新

时间:2016-02-10 10:59:46

标签: javascript mongodb

我希望您对我设置的流程有意见:

我有两个系列:

  

客户:{client_id,client_type}

     

订单:{order_id,client_id,order_amount,order_valid}

根据这些收藏品,我想根据客户类型计算有效订单的数量。

所以我想加入这两个集合并将client_type添加到我的订单集合

我这样做了,但我觉得这个解决方案没有效果。

db.clients.find (
    {},
    {
        client_id : 1,
        client_type : 1
    }   
).forEach(function (pClient) {

    db.orders.update (
        {
            client_id : pClient.client_id
        },
        { $set : {
            client_type : pClient.client_type

        }}, 
        { 
            multi : true
        }
    )
});

您是否知道如何改善这一过程?

1 个答案:

答案 0 :(得分:0)

所以,这是我找到的最快的解决方案:

var bulk = db.orders.initializeUnorderedBulkOp();
var bulk_counter = 0;

db.clients.find (
    {},
    {
        client_id : 1,
        client_type : 1
    }   
).forEach(function (pClient) {
    bulk.find(
        {
            client_id : pClient.client_id
        }
    ).update(
        { $set : {
             client_type : pClient.client_type
        }}, 
    )

    bulk_counter++;
    if (bulk_counter % 1000 == 0) 
    {
        bulk.execute();
        bulk = db.m_recipient_indicators.initializeUnorderedBulkOp();
        }
});

if (bulk_counter % 1000 != 0) 
{ 
    bulk.execute(); 
}