Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add and remove elements in array in Mongo use Java?

Tags:

java

mongodb

So I have object:

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

And I want to delete from "employee_id" array [3, 5] and add new array [13, 6, 8]. And result will be:

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

I use this Java-code:

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);

So how to set in projectMongoObject new array and delete array?

like image 610
somebody Avatar asked Aug 27 '26 06:08

somebody


1 Answers

Make use of the $pullAll operator to remove the fields, and the combination of $push and $each to add new fields to the array.

   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);
like image 83
BatScream Avatar answered Aug 29 '26 21:08

BatScream



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!