6

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 ?

Sumit D
  • 401
  • 4
  • 15

2 Answers2

4

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>);
user1568967
  • 1,816
  • 2
  • 16
  • 18
  • This answer looks good at first, except that you are hard-coding "fs.files". There is no actual guarantee that this is the collection used in the application (it may be different due to configuration). But indeed, using GridFsTemplate, you cannot do this, it seams... – Wouter Jun 01 '14 at 14:03
  • This is meant as a sample. given that Mongo GridFS creates two collections by default (fs.files. fs.chunks) it is left to the implementer to use the appropriate (overridden or not) collection name. GridFsTemplate does not allow for metadata manipulation, you have to rely on an implementation of mongoOperations like MongoTemplate. – user1568967 Jun 03 '14 at 14:39
  • Your solution is good but becuase @Sumit wants to update only 1 field just use `mongoOperations.getCollection("fs.files").update(, )` – royB Dec 18 '14 at 10:22
4

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();
        }
Francesca Merighi
  • 317
  • 1
  • 3
  • 10