当前位置:   article > 正文

MongoDB Java Driver 使用_bucket.opendownloadstreambyname

bucket.opendownloadstreambyname

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. // //SSL
  11. // new MongoClientURI("mongodb://localhost/?ssl=true")
  12. // MongoClientOptions.builder().sslEnabled(true).build()
  13. try {
  14. // ServerAddress sa = new ServerAddress("localhost", 27017);
  15. // List<MongoCredential> mongoCredentialList = new ArrayList<MongoCredential>();
  16. // mongoCredentialList.add(MongoCredential.createCredential("zhou", "zhou", "zhou".toCharArray()));
  17. // mongoClient = new MongoClient(sa, mongoCredentialList,options);
  18. MongoClientURI uri = new MongoClientURI("mongodb://zhou:zhou@127.0.0.1:27017/?authSource=zhou",build);
  19. 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. // replace a document
  8. mongoCollection.replaceOne(Filters.eq("_id", document.get("_id")), document);
  9. // find documents
  10. 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);

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);

count document in a collection:

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

query the collection:

1、find first document

  1. Document myDoc = mongoCollection.find().first();
  2. 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. }

get a single document with a query filter:

  1. Document myDoc = mongoCollection.find(Filters.eq("i", 2)).first();
  2. 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);

sort documents:

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

projecting fields:

  1. Document myDoc = mongoCollection.find().projection(Projections.excludeId()).first();
  2. 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());

updating document:

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());

deleting document:

  1. mongoCollection.deleteOne(Filters.eq("i", 210));
  2. DeleteResult deleteResult = mongoCollection.deleteMany(Filters.gte("i", 100));
  3. 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. // 2. Unordered bulk operation - no guarantee of order of operation
  12. mongoCollection.bulkWrite(
  13. Arrays.asList(new InsertOneModel<Document>(new Document("_id", 4)),
  14. new InsertOneModel<Document>(new Document("_id", 5)),
  15. new InsertOneModel<Document>(new Document("_id", 6)),
  16. new UpdateOneModel<Document>(new Document("_id", 1),
  17. new Document("$set", new Document("x", 2))),
  18. new DeleteOneModel<Document>(new Document("_id", 2)),
  19. new ReplaceOneModel<Document>(new Document("_id", 3),
  20. new Document("_id", 3).append("x", 4))),
  21. 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. // Create some custom options
  5. GridFSUploadOptions gridFSUploadOptions = new GridFSUploadOptions()
  6. .chunkSizeBytes(1024)
  7. .metadata(new Document("type", "presentation"));
  8. ObjectId fileId = gridFSBucket.uploadFromStream("mongodb-tutorial", streamToUploadFrom, gridFSUploadOptions);
  9. 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());


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. });


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());

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>


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. 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. System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8));

Renaming files

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


Deleting files
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. @Override
  15. public void commandSucceeded(final CommandSucceededEvent event) {
  16. System.out.println(String.format("Successfully executed command '%s' with id %s "
  17. + "on connection '%s' to server '%s'",
  18. event.getCommandName(),
  19. event.getRequestId(),
  20. event.getConnectionDescription()
  21. .getConnectionId(),
  22. event.getConnectionDescription().getServerAddress()));
  23. }
  24. @Override
  25. public void commandFailed(final CommandFailedEvent event) {
  26. System.out.println(String.format("Failed execution of command '%s' with id %s "
  27. + "on connection '%s' to server '%s' with exception '%s'",
  28. event.getCommandName(),
  29. event.getRequestId(),
  30. event.getConnectionDescription()
  31. .getConnectionId(),
  32. event.getConnectionDescription().getServerAddress(),
  33. event.getThrowable()));
  34. }
  35. } </span>

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


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/220880
推荐阅读
相关标签
  

闽ICP备14008679号