3

I'm working on creating a web-based viewer for MongoDB and want to list the buckets available in GridFS. Unless I get the bucket name, I won't be able to list the files contained in the bucket. I have searched the mongo-java documentation but couldn't find any API for getting the bucket names. Is there any java API available or an alternative solution to get the list of bucket names ?

4

1 に答える 1

1

バケットのリストを直接取得する方法はないと思います。バケットを明示的に指定する必要があるため、これはおそらくほとんど必要ありません。そのため、通常、何を探すべきかを知ってデータベースにアクセスします。

コレクション名を調べて、このようなことを行うのはやや厄介な解決策です (もちろん、誰かがたまたまいくつかのコレクションに「.chunks」と「.files」というラベルを付けた場合、おそらく誤解を招く結果になるでしょう):

GridFS fs = new GridFS(db, "buck");
fs.createFile();
fs = new GridFS(db, "bucket");
fs.createFile();
fs = new GridFS(db, "test");
fs.createFile();
Set<String> colls = db.getCollectionNames();
for(String collName : colls) {
   if(collName.endsWith(".chunks")) {
      String potentialBucketName = collName.substring(0,collName.indexOf(".chunks"));
      if(colls.contains(potentialBucketName+".files")) {
         System.out.println(potentialBucketName + " is a bucket");
      }
   }
}

結果を与える:

buck is a bucket
bucket is a bucket
test is a bucket
于 2012-03-14T08:56:21.770 に答える