如何在GridFS中执行更新操作(使用Java)? [英] How to perform Update operations in GridFS (using Java)?

查看:891
本文介绍了如何在GridFS中执行更新操作(使用Java)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Mongo-Java-Driver 2.13 我在 GridFS 中存储了一个PDF文件( size 30mb ) 。我能够轻松地执行插入,删除和查找操作。

I am using Mongo-Java-Driver 2.13 I stored a PDF file (size 30mb) in GridFS. I am able to perform insertion, deletion and find operation easily.

    MongoClient mongo = new MongoClient("localhost", 27017);
    DB db = mongo.getDB("testDB");
    File pdfFile = new File("/home/dev/abc.pdf");
    GridFS gfs = new GridFS(db,"books");     
    GridFSInputFile inputFile = gfs.createFile(pdfFile);
    inputFile.setId("101");
    inputFile.put("title", "abc");
    inputFile.put("author", "xyz");
    inputFile.save();

数据保存在 books.files books.chunks 集合。现在我要更新

data is persisted in books.files and books.chunks collections. Now I want to update :


  • 案例1:pdf文件

  • 案例2:标题或作者


如何为案例1执行这些更新操作在GridFS中?

我发现我需要维护我的文件的多个版本并选择正确的版本。有人可以说清楚吗?

I came to know that I need to maintain multiple versions of my files and pick up the right version. Can anybody put some clarity on it?

编辑

我可以更新元数据(标题,作者)很容易。

I can update metadata(title, author) easily.

    GridFSDBFile outputFile = gfs.findOne(new BasicDBObject("_id", 101));
    BasicDBObject updatedMetadata = new BasicDBObject();
    updatedMetadata.put("name", "PG");
    updatedMetadata.put("age", 22);

    outputFile.setMetaData(newMetadata);       
    outputFile.save();


推荐答案

在GridFS中,您不会删除/删除单个文档但实际上是一堆文件(文件被分成块,每个块都是一个单独的文件)。这意味着以原子方式替换文件是不可能的。

In GridFS you are not removing/deleting a single document but actually a bunch of documents (files are split into chunks and each chunk is a separate document). That means replacing a file is simply not possible in an atomic manner.

你可以做的是:


  1. 在发生这种情况后插入一个新名称

  2. 的新文件(使用副本确认的写入问题),更新所有引用在您收到确认后,将旧文件指向新文件

  3. ,您可以删除旧文件

  1. insert a new file with a new name
  2. after this happened (use the replica acknowledged write-concern), update all references to the old file to point to the new one
  3. after you got a confirmation for this, you can delete the old file

GridFS是一种hackish功能。通常最好只使用带有真实文件系统的单独文件服务器来存储文件内容,并仅将元数据存储在MongoDB中。

GridFS is kind of a hackish feature. It is often better to just use a separate fileserver with a real filesystem to store the file content and only store the metadata in MongoDB.

这篇关于如何在GridFS中执行更新操作(使用Java)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆