I'm using MongoDB 3.2 and MongoDB Java Driver 3.2. In order to update the document I use the following code:
unfetchedEpisodes.stream()
.forEach(ep -> {
BasicDBObject updatedFields = new BasicDBObject();
updatedFields.append("fetchStatus", "IN_PROCESS");
updateColFields(updatedFields, dbCollection, new ObjectId(ep.get("_id").toString()));
});
public void updateColFields(BasicDBObject updatedFields, MongoCollection<Document> dbCollection, ObjectId docID) {
BasicDBObject setQuery = new BasicDBObject();
setQuery.append("$set", updatedFields);
BasicDBObject searchQuery = new BasicDBObject("_id", docID);
dbCollection.updateOne(searchQuery, setQuery);
}
This code works but I'm not sure that this code updates only the specific field (e.g. fetchStatus
) of the document and not overwrites the whole document.
Does this code update only the specific field of the document or simply overwrites the whole document?
It just updates the specified field. The field will be created if it doesn't exist. Other fields remain untouched. According to documentation:
The $set operator replaces the value of a field with the specified value.
and
If the field does not exist, $set will add a new field with the specified value, provided that the new field does not violate a type constraint. If you specify a dotted path for a non-existent field, $set will create the embedded documents as needed to fulfill the dotted path to the field.