I want to update single field of metadata in GrifFs files collection.
I read the documentation about Spring Data MongoDB but did not find any API for that.
The only solution I have found so far is to use the Mongo API directly to delete the existing file, and store a new one with the same _id
. But this is not effective solution. The problem is specific to Spring Data MongoDB . any alternative ?
use mongoOperations.
the metadata is stored in the collection fs.files; if you are only updating the metadata you can access it by using the collection directly and update it:
DBObject yourObjectWithMetadata = mongoOperations.getCollection("fs.files").findOne(<Object Id>);
mongoOperations.getCollection("fs.files").save(<your db object with updated metadata>);
Another solution to add or entirely replace metadata fields.
Map<String,Object> fields=...;
Replacing metadata:
List<GridFSDBFile> files = gfs.find(query);
for (GridFSDBFile file : files) {
file.setMetaData(new BasicDBObject(fields));
file.save();
}
Adding metadata:
List<GridFSDBFile> files = gfs.find(query);
for (GridFSDBFile file : files) {
if (file.getMetaData() == null)
file.setMetaData(new BasicDBObject(fields));
else
file.getMetaData().putAll(fields);
file.save();
}
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