How to search a document and remove field from it in mongodb using java?
You can remove a field using $unset
with mongo-java driver in this way:
MongoClient mongo = new MongoClient("localhost", 27017); DB db = (DB) mongo.getDB("testDB"); DBCollection collection = db.getCollection("collection"); DBObject query = new BasicDBObject("_id", "10-100-5675234"); DBObject update = new BasicDBObject(); update.put("$unset", new BasicDBObject("userId","")); WriteResult result = collection.update(query, update); mongo.close();
The easiest way is to use the functionality in the java driver:
Query query = new Query();query.addCriteria(Criteria.where("_id").is(new ObjectId("10-100-5675234")));Update update = new Update();update.unset("userId"); //the fields you want to removeupdate.set("putInYourFieldHere", "putInYourValueHere"); //the fields you want to addmongoTemplate.updateFirst(query, update, Device.class);
The above code assumes that your "_id"
is your mongodb normal "_id"
which means that the variable you are looking for must be encased in the new ObjectId()
.
An ugly way is to replace the old version with the new version of you document (no userid).
BasicDBObject newDocument = new BasicDBObject();newDocument.put("_type", "Device");newDocument.put("alias", "new Alias name");// ... BasicDBObject searchQuery = new BasicDBObject().append("_id", "10-100-5675234");collection.update(searchQuery, newDocument);