Convert MongoShell code to java code

时间:2016-04-25 09:31:30

标签: java mongodb

I'm trying to convert the below mongo shell code into java code.

I'm trying to update the EMP_SALARY of all employees over here.How can I convert this mongo code to java.

Can anyone please help me out regarding this...

{
            "_id" : ObjectId("571898dbc000041fe0b921eb"),
            "ORGANIZATION" : "abc",
            "TOTAL_EMPLOYEES" : 10,
            "TOTAL_EMPLOYEES_SALARY" : 0,

            "employees" : [
                    {
                            "EMP_NAME" : "vijay",
                            "EMP_SALARY" : 2000,

                    },
                    {
                            "EMP_NAME" : "vishnu",
                            "EMP_SALARY" : 3000,

                    },
                    {
                            "EMP_NAME" : "vishal",
                            "EMP_SALARY" : 4000,

                    }
            ]
    }

Mongoshell code:

var ops = [];

db.collection.find().forEach(function(doc) {
    doc.employees.forEach(function(emp) {
        ops.push({
            "updateOne": {
                "filter": { "_id": doc._id },
                "update": { 
                    "$inc": { 
                        "TOTAL_EMPLOYEE_SALARY": emp.EMP_SALARY
                    }
                }
            }
        });

        if ( ops.length == 1000 ) {
            db.collection.bulkWrite(ops);
            ops = [];
        }
    })
});

if ( ops.length > 0 ) {
    db.collection.bulkWrite(ops);
}

0 个答案:

没有答案