Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 497
Swapnil1988 Avatar asked Apr 01 '15 11:04

Swapnil1988


People also ask

How do I remove a field from a document in MongoDB?

In MongoDB, you can use the $unset field update operator to completely remove a field from a document. The $unset operator is designed specifically to delete a field and its value from the document.

How do you delete a record in MongoDB Java?

You can delete a single document from a collection using the deleteOne() method on a MongoCollection object. The method accepts a query filter that matches the document you want to delete. If you do not specify a filter, MongoDB matches the first document in the collection.

How do I search for a specific field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});


3 Answers

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();
like image 190
Dev Avatar answered Oct 20 '22 01:10

Dev


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 remove
update.set("putInYourFieldHere", "putInYourValueHere"); //the fields you want to add
mongoTemplate.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().

like image 31
Simon Avatar answered Oct 20 '22 00:10

Simon


Long time since this post was opened, but might be useful for someone in the future.

device.updateMany(eq("_id", "whatever"), unset("userId"));
like image 40
Calfa Avatar answered Oct 19 '22 23:10

Calfa