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.
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.
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.
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
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 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()
.
Long time since this post was opened, but might be useful for someone in the future.
device.updateMany(eq("_id", "whatever"), unset("userId"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With