Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating GridFS metadata using Spring Data MongoDB

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 ?

like image 405
Sumit D Avatar asked Mar 21 '14 11:03

Sumit D


2 Answers

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>);
like image 129
user1568967 Avatar answered Nov 01 '22 11:11

user1568967


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();
        }
like image 4
Francesca Merighi Avatar answered Nov 01 '22 12:11

Francesca Merighi