javamongodbmongodb-querymongo-java-driver

How to search a document and remove field from it in mongodb using java?


I have a device collection.

{
   "_id" : "10-100-5675234",
   "_type" : "Device",
   "alias" : "new Alias name", 
   "claimCode" : "FG755DF8N", 
   "hardwareId" : "SERAIL02",
   "isClaimed" : "true",
   "model" : "VMB3010", 
   "userId" : "5514f428c7b93d48007ac6fd" 
 }

I want to search document by _id and then update it after removing a field userId from the result document. I am trying different ways but none of them is working. Please help me.


Solution

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