How to add new field to existing document in mongodb using java?
Answer Posted / Poonam Kushwaha
To add a new field to an existing document in MongoDB using Java, you can use the updateOne() method of MongoCollection. Here's an example:
```java
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class AddFieldExample {
public static void main(String[] args) {
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection("mycollection");
// Update an existing document by adding a field
Document filter = new Document("_id", new ObjectId("507f1f77810c19762dfa6cea"));
Document update = new Document("$set", new Document("newField", "newValue"));
collection.updateOne(filter, update);
}
}
| Is This Answer Correct ? | 0 Yes | 0 No |
Post New Answer View All Answers