MongoDB 3.0之Java API使用

import java.util.*;
import org.bson.Document;  
import org.bson.conversions.Bson;  
  
import com.mongodb.BasicDBObject;  
import com.mongodb.Block;  
import com.mongodb.MongoClient;  
import com.mongodb.client.*;  
import com.mongodb.client.model.BulkWriteOptions;  
import com.mongodb.client.model.DeleteOneModel;  
import com.mongodb.client.model.InsertOneModel;  
import com.mongodb.client.model.ReplaceOneModel;  
import com.mongodb.client.model.UpdateOneModel;  
import com.mongodb.client.result.DeleteResult;  
import com.mongodb.client.result.UpdateResult;  
  
import static com.mongodb.client.model.Filters.*;  
  
/** 
 * 程序入口 
 *  
 * @author John 
 * 
 */  
public class testmain {  
    public static void main(String[] args) {  
        testmain tm = new testmain();  
        tm.test();  
    }  
  
    /** 
     * test 
     */  
    private void test() {  
        // 获取链接  
        MongoClient mongoClient = new MongoClient("localhost", 27017);  
        // 获取数据库  
        MongoDatabase database = mongoClient.getDatabase("mydb");  
        // 进入某个文档集  
        MongoCollection<Document> collection = database.getCollection("test");  
  
        /********************** 数据插入 ****************************/  
        // 创建新文档  
        // Document doc = new Document("name", "MongoDB")  
        // .append("type", "database").append("count", 1)  
        // .append("info", new Document("x", 203).append("y", 102));  
        // 将文档插入文档集合  
        // collection.insertOne(doc);  
  
        // 创建一个包含多个文档的列表  
        // List<Document> documents = new ArrayList<Document>();  
        // for (int i = 0; i < 100; i++) {  
        // documents.add(new Document("i", i));  
        // }  
        // 向文档中插入列表  
        // collection.insertMany(documents);  
  
        /***************** 数据读取 ****************************************/  
        // // 显示集合中的文档的数量  
        // System.out.println(collection.count());  
        // 查询集合中的第一个文档  
        // Document myDoc = collection.find().first();  
        // System.out.println(myDoc.toJson());  
  
        //获取集合中的全部文档  
        // MongoCursor<Document> cursor = collection.find().iterator();  
        // try {  
        // while (cursor.hasNext()) {  
        // System.out.println(cursor.next().toJson());  
        // }  
        // } finally {  
        // cursor.close();  
        // }  
  
        //获取全部文档的另一种方法  
        // for (Document cur : collection.find()) {  
        // System.out.println(cur.toJson());  
        // }  
  
        // // 根据条件获取某分文档 eq:==  
        // Document myDoc = collection.find(eq("i", 71)).first();  
        // System.out.println(myDoc.toJson());  
  
        // 通过查询语句一次性获取多个数据  
        // Block<Document> printBlock = new Block<Document>() {  
        // @Override  
        // public void apply(final Document document) {  
        // System.out.println(document.toJson());  
        // }  
        // };  
        // 获得所有大于50的  
        // collection.find(gt("i", 50)).forEach(printBlock);  
        // 大于50 小于 100  
        // collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock);  
  
        // 对输出文档进行排序,-1为递减,1为递增  
        // 官方文档的例子有误:http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/#sorting-documents  
        // Document myDoc = collection.find(exists("i"))  
        // .sort(new BasicDBObject("i", -1)).first();  
        // System.out.println(myDoc.toJson());  
  
        // 选择性输出结果中的元素,0为不显示,1为显示  
        // 官方文档中的例子又不能用:http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/#projecting-fields  
        // BasicDBObject exclude = new BasicDBObject();  
        // exclude.append("_id", 0);  
        // exclude.append("count", 0);  
        // exclude.append("name", 1);  
        // exclude.append("info", 1);  
        // Document myDoc = collection.find().projection(exclude).first();  
        // System.out.println(myDoc.toJson());  
  
        /************************* 修改数据库中数据 *************************************/  
  
        // 修改时的参数:  
        // $inc 对指定的元素加  
        // $mul 乘  
        // $rename 修改元素名称  
        // $setOnInsert 如果以前没有这个元素则增加这个元素,否则不作任何更改  
        // $set 修改制定元素的值  
        // $unset 移除特定的元素  
        // $min 如果原始数据更大则不修改,否则修改为指定的值  
        // $max 与$min相反  
        // $currentDate 修改为目前的时间  
  
        // //修改第一个符合条件的数据  
        // $set 为修改  
        // collection.updateOne(eq("i", 10), new Document("$set", new  
        // Document("i", 110)));  
        // // 获取全部文档,可以看到以前10的地方变成了110  
        // for (Document cur : collection.find()) {  
        // System.out.println(cur.toJson());  
        // }  
  
        // 批量修改数据并且返回修改的结果,讲所有小于100的结果都加100  
        // UpdateResult updateResult = collection.updateMany(lt("i", 100),  
        // new Document("$inc", new Document("i", 100)));  
        // // 显示发生变化的行数  
        // System.out.println(updateResult.getModifiedCount());  
        // // 获取全部文档,可以看到除了刚才修改的110其他的全为了100  
        // for (Document cur : collection.find()) {  
        // System.out.println(cur.toJson());  
        // }  
  
        /************************** 删除数据 *****************************/  
        // 删除第一个符合条件的数据  
        // collection.deleteOne(eq("i", 110));  
        // // 获取全部文档,可以看到没有110这个数了  
        // for (Document cur : collection.find()) {  
        // System.out.println(cur.toJson());  
        // }  
  
        // 删除所有符合条件的数据,并且返回结果  
        // DeleteResult deleteResult = collection.deleteMany(gte("i", 100));  
        // // 输出删除的行数  
        // System.out.println(deleteResult.getDeletedCount());  
        // // 获取全部文档,所有i>=100的数据都没了  
        // for (Document cur : collection.find()) {  
        // System.out.println(cur.toJson());  
        // }  
        /*************************** 程序块,一次执行多条语句 ********************************/  
        // 按照语句先后顺序执行  
        // collection.bulkWrite(Arrays.asList(new InsertOneModel<>(new Document(  
        // "_id", 4)), new InsertOneModel<>(new Document("_id", 5)),  
        // new InsertOneModel<>(new Document("_id", 6)),  
        // new UpdateOneModel<>(new Document("_id", 1), new Document(  
        // "$set", new Document("x", 2))), new DeleteOneModel<>(  
        // new Document("_id", 2)),  
        // new ReplaceOneModel<>(new Document("_id", 3), new Document(  
        // "_id", 3).append("x", 4))));  
        // // 获取全部文档  
        // for (Document cur : collection.find()) {  
        // System.out.println(cur.toJson());  
        // }  
  
        // 不按照语句先后顺序执行  
        // collection.bulkWrite(Arrays.asList(new InsertOneModel<>(new Document(  
        // "_id", 4)), new InsertOneModel<>(new Document("_id", 5)),  
        // new InsertOneModel<>(new Document("_id", 6)),  
        // new UpdateOneModel<>(new Document("_id", 1), new Document(  
        // "$set", new Document("x", 2))), new DeleteOneModel<>(  
        // new Document("_id", 2)),  
        // new ReplaceOneModel<>(new Document("_id", 3), new Document(  
        // "_id", 3).append("x", 4))), new BulkWriteOptions()  
        // .ordered(false));  
        // 获取全部文档  
        // for (Document cur : collection.find()) {  
        // System.out.println(cur.toJson());  
        // }  
          
          
        // 关闭数据库连接  
        mongoClient.close();  
  
    }  
  
}  


 

 

1、connect & authenticate &SSL

  1. MongoClientOptions.Builder build = new MongoClientOptions.Builder();  
  2.         //与数据最大连接数50  
  3.         build.connectionsPerHost(50);  
  4.         //如果当前所有的connection都在使用中,则每个connection上可以有50个线程排队等待  
  5.         build.threadsAllowedToBlockForConnectionMultiplier(50);  
  6.         build.connectTimeout(1*60*1000);  
  7.         build.maxWaitTime(2*60*1000);  
  8.         MongoClientOptions options = build.build();  
  9.         MongoClient mongoClient = null;  
  10.   
  11. //        //SSL  
  12. //        new MongoClientURI("mongodb://localhost/?ssl=true")  
  13. //        MongoClientOptions.builder().sslEnabled(true).build()  
  14.         try {  
  15. //            ServerAddress sa = new ServerAddress("localhost", 27017);  
  16. //            List<MongoCredential> mongoCredentialList = new ArrayList<MongoCredential>();  
  17. //            mongoCredentialList.add(MongoCredential.createCredential("zhou", "zhou", "zhou".toCharArray()));  
  18. //            mongoClient = new MongoClient(sa, mongoCredentialList,options);  
  19.   
  20.   
  21.   
  22.             MongoClientURI uri = new MongoClientURI("mongodb://zhou:zhou@127.0.0.1:27017/?authSource=zhou",build);  
  23.             mongoClient = new MongoClient(uri);  
MongoClientOptions.Builder build = new MongoClientOptions.Builder();
        //与数据最大连接数50
        build.connectionsPerHost(50);
        //如果当前所有的connection都在使用中,则每个connection上可以有50个线程排队等待
        build.threadsAllowedToBlockForConnectionMultiplier(50);
        build.connectTimeout(1*60*1000);
        build.maxWaitTime(2*60*1000);
        MongoClientOptions options = build.build();
        MongoClient mongoClient = null;

//        //SSL
//        new MongoClientURI("mongodb://localhost/?ssl=true")
//        MongoClientOptions.builder().sslEnabled(true).build()
        try {
//            ServerAddress sa = new ServerAddress("localhost", 27017);
//            List<MongoCredential> mongoCredentialList = new ArrayList<MongoCredential>();
//            mongoCredentialList.add(MongoCredential.createCredential("zhou", "zhou", "zhou".toCharArray()));
//            mongoClient = new MongoClient(sa, mongoCredentialList,options);



            MongoClientURI uri = new MongoClientURI("mongodb://zhou:zhou@127.0.0.1:27017/?authSource=zhou",build);
            mongoClient = new MongoClient(uri);


2、CRUD

  1. MongoDatabase mongoDatabase = mongoClient.getDatabase("zhou");  
  2.             MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("user");  
  3.             // insert a document  
  4.             Document document = new Document("x"1);  
  5.             mongoCollection.insertOne(document);  
  6.             document.append("x"2).append("y"3);  
  7.   
  8.             // replace a document  
  9.             mongoCollection.replaceOne(Filters.eq("_id", document.get("_id")), document);  
  10.   
  11.             // find documents  
  12.             List<Document> foundDocument = mongoCollection.find().into(new ArrayList<Document>());  
MongoDatabase mongoDatabase = mongoClient.getDatabase("zhou");
            MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("user");
            // insert a document
            Document document = new Document("x", 1);
            mongoCollection.insertOne(document);
            document.append("x", 2).append("y", 3);

            // replace a document
            mongoCollection.replaceOne(Filters.eq("_id", document.get("_id")), document);

            // find documents
            List<Document> foundDocument = mongoCollection.find().into(new ArrayList<Document>());


insert adocument:

  1. // insert a document  
  2.             Document doc = new Document("name""MongoDB")  
  3.                     .append("type""database")  
  4.                     .append("count"1)  
  5.                     .append("info"new Document("x"203).append("y"102));  
  6.             mongoCollection.insertOne(doc);  
// insert a document
            Document doc = new Document("name", "MongoDB")
                    .append("type", "database")
                    .append("count", 1)
                    .append("info", new Document("x", 203).append("y", 102));
            mongoCollection.insertOne(doc);


add mutiple document:

  1. List<Document> documents = new ArrayList<Document>();  
  2.             for (int i = 0; i < 5; i++) {  
  3.                 documents.add(new Document("i", i));  
  4.             }  
  5.             mongoCollection.insertMany(documents);  
List<Document> documents = new ArrayList<Document>();
            for (int i = 0; i < 5; i++) {
                documents.add(new Document("i", i));
            }
            mongoCollection.insertMany(documents);


count document in a collection:

  1. for (Document cur : mongoCollection.find()) {  
  2.                 System.out.println(cur.toJson());  
  3.             }  
for (Document cur : mongoCollection.find()) {
                System.out.println(cur.toJson());
            }

query the collection:

1、find first document

  1. Document myDoc = mongoCollection.find().first();  
  2.             System.out.println(myDoc.toJson());  
Document myDoc = mongoCollection.find().first();
            System.out.println(myDoc.toJson());


2、find all documents in a collection:

  1. MongoCursor<Document> cursor = mongoCollection.find().iterator();  
  2.             try {  
  3.                 while (cursor.hasNext()) {  
  4.                     System.out.println(cursor.next().toJson());  
  5.                 }  
  6.             } finally {  
  7.                 cursor.close();  
  8.             }  
MongoCursor<Document> cursor = mongoCollection.find().iterator();
            try {
                while (cursor.hasNext()) {
                    System.out.println(cursor.next().toJson());
                }
            } finally {
                cursor.close();
            }


get a single document with a query filter:

  1. Document myDoc = mongoCollection.find(Filters.eq("i"2)).first();  
  2.             System.out.println(myDoc.toJson());  
Document myDoc = mongoCollection.find(Filters.eq("i", 2)).first();
            System.out.println(myDoc.toJson());


get a set of document with a query:

  1. Block<Document> printBlock = new Block<Document>() {  
  2.                 @Override  
  3.                 public void apply(final Document document) {  
  4.                     System.out.println(document.toJson());  
  5.                 }  
  6.             };  
  7.             mongoCollection.find(Filters.gt("i"1)).forEach(printBlock);  
  8.             mongoCollection.find(Filters.and(Filters.gt("i"2), Filters.lte("i"4))).forEach(printBlock);  
Block<Document> printBlock = new Block<Document>() {
                @Override
                public void apply(final Document document) {
                    System.out.println(document.toJson());
                }
            };
            mongoCollection.find(Filters.gt("i", 1)).forEach(printBlock);
            mongoCollection.find(Filters.and(Filters.gt("i", 2), Filters.lte("i", 4))).forEach(printBlock);


sort documents:

  1. Document myDoc = mongoCollection.find(Filters.exists("i")).sort(Sorts.descending("i")).first();  
  2.             System.out.println(myDoc.toJson());  
Document myDoc = mongoCollection.find(Filters.exists("i")).sort(Sorts.descending("i")).first();
            System.out.println(myDoc.toJson());


projecting fields:

  1. Document myDoc = mongoCollection.find().projection(Projections.excludeId()).first();  
  2.             System.out.println(myDoc.toJson());  
Document myDoc = mongoCollection.find().projection(Projections.excludeId()).first();
            System.out.println(myDoc.toJson());


Aggregations:

  1. mongoCollection.aggregate(Arrays.asList(  
  2.                             Aggregates.match(Filters.gt("i"0)),  
  3.                             Aggregates.project(Document.parse("{times: {$multiply: ['$i', 10]}}")))  
  4.             ).forEach(printBlock);  
  5.             Document myDoc = mongoCollection.aggregate(Collections.singletonList(Aggregates.group(null, Accumulators.sum("total""$i")))).first();  
  6.             System.out.println(myDoc.toJson());  
mongoCollection.aggregate(Arrays.asList(
                            Aggregates.match(Filters.gt("i", 0)),
                            Aggregates.project(Document.parse("{times: {$multiply: ['$i', 10]}}")))
            ).forEach(printBlock);
            Document myDoc = mongoCollection.aggregate(Collections.singletonList(Aggregates.group(null, Accumulators.sum("total", "$i")))).first();
            System.out.println(myDoc.toJson());


updating document:

  1. mongoCollection.updateOne(Filters.eq("i"1), Updates.set("i"110));  
mongoCollection.updateOne(Filters.eq("i", 1), Updates.set("i", 110));

  1. UpdateResult updateResult = mongoCollection.updateMany(Filters.gte("i"1), Updates.inc("i"100));  
  2.             System.out.println(updateResult.getModifiedCount());  
UpdateResult updateResult = mongoCollection.updateMany(Filters.gte("i", 1), Updates.inc("i", 100));
            System.out.println(updateResult.getModifiedCount());


deleting document:

  1. mongoCollection.deleteOne(Filters.eq("i"210));  
  2.             DeleteResult deleteResult = mongoCollection.deleteMany(Filters.gte("i"100));  
  3.             System.out.println(deleteResult.getDeletedCount());  
mongoCollection.deleteOne(Filters.eq("i", 210));
            DeleteResult deleteResult = mongoCollection.deleteMany(Filters.gte("i", 100));
            System.out.println(deleteResult.getDeletedCount());

bulk operations :

  1. // 1. Ordered bulk operation - order is guarenteed  
  2.             mongoCollection.bulkWrite(  
  3.                     Arrays.asList(new InsertOneModel<Document>(new Document("_id"4)),  
  4.                             new InsertOneModel<Document>(new Document("_id"5)),  
  5.                             new InsertOneModel<Document>(new Document("_id"6)),  
  6.                             new UpdateOneModel<Document>(new Document("_id"1),  
  7.                                     new Document("$set"new Document("x"2))),  
  8.                             new DeleteOneModel<Document>(new Document("_id"2)),  
  9.                             new ReplaceOneModel<Document>(new Document("_id"3),  
  10.                                     new Document("_id"3).append("x"4))));  
  11.   
  12.   
  13.             // 2. Unordered bulk operation - no guarantee of order of operation  
  14.             mongoCollection.bulkWrite(  
  15.                     Arrays.asList(new InsertOneModel<Document>(new Document("_id"4)),  
  16.                             new InsertOneModel<Document>(new Document("_id"5)),  
  17.                             new InsertOneModel<Document>(new Document("_id"6)),  
  18.                             new UpdateOneModel<Document>(new Document("_id"1),  
  19.                                     new Document("$set"new Document("x"2))),  
  20.                             new DeleteOneModel<Document>(new Document("_id"2)),  
  21.                             new ReplaceOneModel<Document>(new Document("_id"3),  
  22.                                     new Document("_id"3).append("x"4))),  
  23.                     new BulkWriteOptions().ordered(false));  
// 1. Ordered bulk operation - order is guarenteed
            mongoCollection.bulkWrite(
                    Arrays.asList(new InsertOneModel<Document>(new Document("_id", 4)),
                            new InsertOneModel<Document>(new Document("_id", 5)),
                            new InsertOneModel<Document>(new Document("_id", 6)),
                            new UpdateOneModel<Document>(new Document("_id", 1),
                                    new Document("$set", new Document("x", 2))),
                            new DeleteOneModel<Document>(new Document("_id", 2)),
                            new ReplaceOneModel<Document>(new Document("_id", 3),
                                    new Document("_id", 3).append("x", 4))));


            // 2. Unordered bulk operation - no guarantee of order of operation
            mongoCollection.bulkWrite(
                    Arrays.asList(new InsertOneModel<Document>(new Document("_id", 4)),
                            new InsertOneModel<Document>(new Document("_id", 5)),
                            new InsertOneModel<Document>(new Document("_id", 6)),
                            new UpdateOneModel<Document>(new Document("_id", 1),
                                    new Document("$set", new Document("x", 2))),
                            new DeleteOneModel<Document>(new Document("_id", 2)),
                            new ReplaceOneModel<Document>(new Document("_id", 3),
                                    new Document("_id", 3).append("x", 4))),
                    new BulkWriteOptions().ordered(false));



Uploading to GridFS

uploadFromStream

  1. GridFSBucket gridFSBucket = GridFSBuckets.create(mongoDatabase, "files");  
  2.             // Get the input stream  
  3.             InputStream streamToUploadFrom = new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\aa.jpg"));  
  4.   
  5. // Create some custom options  
  6.             GridFSUploadOptions gridFSUploadOptions = new GridFSUploadOptions()  
  7.                     .chunkSizeBytes(1024)  
  8.                     .metadata(new Document("type""presentation"));  
  9.   
  10.             ObjectId fileId = gridFSBucket.uploadFromStream("mongodb-tutorial", streamToUploadFrom, gridFSUploadOptions);  
  11.             System.out.println(fileId);  
GridFSBucket gridFSBucket = GridFSBuckets.create(mongoDatabase, "files");
            // Get the input stream
            InputStream streamToUploadFrom = new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\aa.jpg"));

// Create some custom options
            GridFSUploadOptions gridFSUploadOptions = new GridFSUploadOptions()
                    .chunkSizeBytes(1024)
                    .metadata(new Document("type", "presentation"));

            ObjectId fileId = gridFSBucket.uploadFromStream("mongodb-tutorial", streamToUploadFrom, gridFSUploadOptions);
            System.out.println(fileId);


openUploadStream

  1. byte[] data = "Data to upload into GridFS".getBytes(StandardCharsets.UTF_8);  
  2.            GridFSUploadStream uploadStream = gridFSBucket.openUploadStream("sampleData", gridFSUploadOptions);  
  3.            uploadStream.write(data);  
  4.            uploadStream.close();  
  5.            System.out.println("The fileId of the uploaded file is: " + uploadStream.getFileId().toHexString());  
 byte[] data = "Data to upload into GridFS".getBytes(StandardCharsets.UTF_8);
            GridFSUploadStream uploadStream = gridFSBucket.openUploadStream("sampleData", gridFSUploadOptions);
            uploadStream.write(data);
            uploadStream.close();
            System.out.println("The fileId of the uploaded file is: " + uploadStream.getFileId().toHexString());


Finding files stored in GridFS

  1. gridFSBucket.find(Filters.eq("metadata.type""presentation")).forEach(  
  2.                     new Block<GridFSFile>() {  
  3.                         @Override  
  4.                         public void apply(final GridFSFile gridFSFile) {  
  5.                             System.out.println(gridFSFile.getFilename());  
  6.                         }  
  7.                     });  
gridFSBucket.find(Filters.eq("metadata.type", "presentation")).forEach(
                    new Block<GridFSFile>() {
                        @Override
                        public void apply(final GridFSFile gridFSFile) {
                            System.out.println(gridFSFile.getFilename());
                        }
                    });


Downloading from GridFS

DownloadFromStream

  1. ObjectId fileId = new ObjectId("56cbfe4200b3c32c30a36066");  
  2.             FileOutputStream streamToDownloadTo = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\amyAcker.jpg");  
  3.             gridFSBucket.downloadToStream(fileId, streamToDownloadTo);  
  4.             streamToDownloadTo.close();  
  5.             System.out.println(streamToDownloadTo.toString());  
ObjectId fileId = new ObjectId("56cbfe4200b3c32c30a36066");
            FileOutputStream streamToDownloadTo = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\amyAcker.jpg");
            gridFSBucket.downloadToStream(fileId, streamToDownloadTo);
            streamToDownloadTo.close();
            System.out.println(streamToDownloadTo.toString());


DownloadToStreamByName

  1.             FileOutputStream streamToDownloadTo = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\amyAcker.jpg");  
  2.             GridFSDownloadByNameOptions downloadOptions = new GridFSDownloadByNameOptions().revision(0);  
  3.             gridFSBucket.downloadToStreamByName("mongodb-tutorial", streamToDownloadTo, downloadOptions);  
  4.             streamToDownloadTo.close();<strong>  
  5. </strong>  
            FileOutputStream streamToDownloadTo = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\amyAcker.jpg");
            GridFSDownloadByNameOptions downloadOptions = new GridFSDownloadByNameOptions().revision(0);
            gridFSBucket.downloadToStreamByName("mongodb-tutorial", streamToDownloadTo, downloadOptions);
            streamToDownloadTo.close();<strong>
</strong>


OpenDownloadStream

  1. GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(new ObjectId("56cc003a00b3c32a3474ba3f"));  
  2.             int fileLength = (int) downloadStream.getGridFSFile().getLength();  
  3.             byte[] bytesToWriteTo = new byte[fileLength];  
  4.             downloadStream.read(bytesToWriteTo);  
  5.             downloadStream.close();  
  6.   
  7.             System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8));  
GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(new ObjectId("56cc003a00b3c32a3474ba3f"));
            int fileLength = (int) downloadStream.getGridFSFile().getLength();
            byte[] bytesToWriteTo = new byte[fileLength];
            downloadStream.read(bytesToWriteTo);
            downloadStream.close();

            System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8));


OpenDownloadStreamByName

  1. GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStreamByName("sampleData");  
  2.             int fileLength = (int) downloadStream.getGridFSFile().getLength();  
  3.             byte[] bytesToWriteTo = new byte[fileLength];  
  4.             downloadStream.read(bytesToWriteTo);  
  5.             downloadStream.close();  
  6.   
  7.             System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8));  
GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStreamByName("sampleData");
            int fileLength = (int) downloadStream.getGridFSFile().getLength();
            byte[] bytesToWriteTo = new byte[fileLength];
            downloadStream.read(bytesToWriteTo);
            downloadStream.close();

            System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8));


Renaming files

  1. <span style="font-size:12px;">gridFSBucket.rename(new ObjectId("56cbfe4200b3c32c30a36066"), "mongodbTutorial");</span>  
<span style="font-size:12px;">gridFSBucket.rename(new ObjectId("56cbfe4200b3c32c30a36066"), "mongodbTutorial");</span>


Deleting files

  1. gridFSBucket.delete(new ObjectId("56cc003a00b3c32a3474ba3f"));  
gridFSBucket.delete(new ObjectId("56cc003a00b3c32a3474ba3f"));


JMX Monitoring

  1. <span style="font-size:10px;">public class TestCommandListener implements CommandListener {                          
  2.     @Override                                                                                                          
  3.     public void commandStarted(final CommandStartedEvent event) {                                                      
  4.         System.out.println(String.format("Sent command '%s:%s' with id %s to database '%s' "                           
  5.                                          + "on connection '%s' to server '%s'",                                        
  6.                                          event.getCommandName(),                                                       
  7.                                          event.getCommand().get(event.getCommandName()),                               
  8.                                          event.getRequestId(),                                                         
  9.                                          event.getDatabaseName(),                                                      
  10.                                          event.getConnectionDescription()                                              
  11.                                               .getConnectionId(),                                                      
  12.                                          event.getConnectionDescription().getServerAddress()));                        
  13.     }                                                                                                                  
  14.                                                                                                                        
  15.     @Override                                                                                                          
  16.     public void commandSucceeded(final CommandSucceededEvent event) {                                                  
  17.         System.out.println(String.format("Successfully executed command '%s' with id %s "                              
  18.                                          + "on connection '%s' to server '%s'",                                        
  19.                                          event.getCommandName(),                                                       
  20.                                          event.getRequestId(),                                                         
  21.                                          event.getConnectionDescription()                                              
  22.                                               .getConnectionId(),                                                      
  23.                                          event.getConnectionDescription().getServerAddress()));                        
  24.     }                                                                                                                  
  25.                                                                                                                        
  26.     @Override                                                                                                          
  27.     public void commandFailed(final CommandFailedEvent event) {                                                        
  28.         System.out.println(String.format("Failed execution of command '%s' with id %s "                                
  29.                                          + "on connection '%s' to server '%s' with exception '%s'",                    
  30.                                          event.getCommandName(),                                                       
  31.                                          event.getRequestId(),                                                         
  32.                                          event.getConnectionDescription()                                              
  33.                                               .getConnectionId(),                                                      
  34.                                          event.getConnectionDescription().getServerAddress(),                          
  35.                                          event.getThrowable()));                                                       
  36.     }                                                                                                                  
  37. }  </span>  
<span style="font-size:10px;">public class TestCommandListener implements CommandListener {                        
    @Override                                                                                                        
    public void commandStarted(final CommandStartedEvent event) {                                                    
        System.out.println(String.format("Sent command '%s:%s' with id %s to database '%s' "                         
                                         + "on connection '%s' to server '%s'",                                      
                                         event.getCommandName(),                                                     
                                         event.getCommand().get(event.getCommandName()),                             
                                         event.getRequestId(),                                                       
                                         event.getDatabaseName(),                                                    
                                         event.getConnectionDescription()                                            
                                              .getConnectionId(),                                                    
                                         event.getConnectionDescription().getServerAddress()));                      
    }                                                                                                                
                                                                                                                     
    @Override                                                                                                        
    public void commandSucceeded(final CommandSucceededEvent event) {                                                
        System.out.println(String.format("Successfully executed command '%s' with id %s "                            
                                         + "on connection '%s' to server '%s'",                                      
                                         event.getCommandName(),                                                     
                                         event.getRequestId(),                                                       
                                         event.getConnectionDescription()                                            
                                              .getConnectionId(),                                                    
                                         event.getConnectionDescription().getServerAddress()));                      
    }                                                                                                                
                                                                                                                     
    @Override                                                                                                        
    public void commandFailed(final CommandFailedEvent event) {                                                      
        System.out.println(String.format("Failed execution of command '%s' with id %s "                              
                                         + "on connection '%s' to server '%s' with exception '%s'",                  
                                         event.getCommandName(),                                                     
                                         event.getRequestId(),                                                       
                                         event.getConnectionDescription()                                            
                                              .getConnectionId(),                                                    
                                         event.getConnectionDescription().getServerAddress(),                        
                                         event.getThrowable()));                                                     
    }                                                                                                                
}  </span>


  1. MongoClientOptions options = MongoClientOptions.builder()                              
  2.                                                .addCommandListener(new TestCommandListener())    
  3.                                                .build();      
MongoClientOptions options = MongoClientOptions.builder()                            
                                               .addCommandListener(new TestCommandListener())  
                                               .build();    


  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值