如何在Mongo中使用Java添加和删除数组中的元素?

时间:2014-12-03 08:02:30

标签: java mongodb

所以我有对象:

"_id" : 1,
"employee_id" : [2, 3, 4, 5],
"project_name" : "qwerty"

我想从"employee_id"数组[3, 5]中删除并添加新数组[13, 6, 8]。结果将是:

"_id" : 1,
"employee_id" : [2, 4, 13, 6, 8],
"project_name" : "qwerty"

我使用这个Java代码:

DB database = mongoClient.getDB("employee_service");
DBCollection collectionProject = database.getCollection("project");

DBObject query = new BasicDBObject();
query.put("_id", project.getId());

DBObject projectMongoObject = new BasicDBObject();
projectMongoObject.put("project_name", project.getProjectName());

//something
collectionProject.update(query, projectMongoObject);

那么如何设置projectMongoObject新数组并删除数组?

1 个答案:

答案 0 :(得分:2)

使用$pullAll运算符删除字段,并使用$push and $each的组合将新字段添加到数组中。

   DBObject query = new BasicDBObject();
   query.put("_id", project.getId());   
   DBObject projectMongoObject = new BasicDBObject();
   projectMongoObject.put("$set", new BasicDBObject("project_name",
                                                     project.getProjectName()));
   projectMongoObject.put("$pullAll", 
                          new BasicDBObject("employee_id", new int[]{3,5}));
   collectionProject.update(query, projectMongoObject);
   projectMongoObject = new BasicDBObject();
   projectMongoObject.put("$push", 
                            new BasicDBObject("employee_id",
                                              new BasicDBObject("$each",
                                                            new int[]{13,6,8})));
   collectionProject.update(query, projectMongoObject);