码迷,mamicode.com
首页 > 数据库 > 详细

MongoDB-Java

时间:2016-05-01 23:14:03      阅读:563      评论:0      收藏:0      [点我收藏+]

标签:

使用Java驱动操作MongoDB数据库,主要涉及到连接数据库,文档的增删改查,大文件的上传

官网有详细Java驱动快速指南:http://mongodb.github.io/mongo-java-driver/3.2/driver/getting-started/quick-tour/

1. 连接到MongoDB

这里我是用IP地址和端口号进行连接,分为两种情况,一个是启用了身份验证,一个是没有启用

1 // 没有开启身份验证,指定IP和端口号连接
2 MongoClient mongoClient = new MongoClient("192.168.0.8" , 27017 );
3     
4 // 开启身份验证时,连接Mongodb
5 MongoCredential credential = MongoCredential.createCredential("userName", "database", "password".toCharArray());
6 mongoClient = new MongoClient(new ServerAddress("192.168.0.8" , 27017), Arrays.asList(credential));

2. 文档的插入

 1 MongoDatabase db = mongoClient.getDatabase("mydb");
 2 MongoCollection<Document> col = db.getCollection("foo");
 3 // 单个插入
 4 Document doc = new Document("name", "MongoDB").append("type", "database");
 5 col.insertOne(doc);
 6 // 可以把JSON 字符串直接解析成Document
 7 doc = Document.parse("{‘name‘:‘Java‘, ‘type‘:‘language‘}");
 8 col.insertOne(doc);
 9 
10 // 插入多个文档
11 List<Document> documents = new ArrayList<Document>();
12 for(int i=0; i<10; i++){
13     documents.add(new Document("i", i));
14 }
15 col.insertMany(documents);

3. 文档的增删改查

// 查询全部
MongoCursor<Document> cursor = col.find().iterator();
try {
    while (cursor.hasNext()) {
        System.out.println(cursor.next().toJson());
    }
} finally {
    cursor.close();
}

// 使用查询条件
// 首先导入 import static com.mongodb.client.model.Filters.*;
doc = col.find(eq("i", 5)).first(); // i 等于5 的第一个文档
System.out.println(doc.toJson());

cursor = col.find(and(gt("i", 50), lte("i", 100))).iterator();

try {
    while (cursor.hasNext()) {
        System.out.println(cursor.next().toJson());
    }
} finally {
    cursor.close();
}

// 排序
doc = col.find(exists("i")).sort(descending("i")).first();
System.out.println(doc.toJson());

// 更新一个
col.updateOne(eq("i", 10), set("i", 110));

// 更新多个
UpdateResult updateResult = col.updateMany(lt("i", 100), inc("i", 100));
System.out.println(updateResult.getModifiedCount());

// 删除一个
col.deleteOne(eq("i", 110));

// 删除多个
DeleteResult deleteResult = col.deleteMany(gte("i", 100));
System.out.println(deleteResult.getDeletedCount());

// 批量写入操作
List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>();
writes.add(new InsertOneModel<Document>(new Document("_id", 4)));
writes.add(new InsertOneModel<Document>(new Document("_id", 5)));
writes.add(new InsertOneModel<Document>(new Document("_id", 6)));
writes.add(new UpdateOneModel<Document>(new Document("_id", 1), new Document("$set", new Document("x", 2))));
writes.add(new DeleteOneModel<Document>(new Document("_id", 2)));
writes.add(new ReplaceOneModel<Document>(new Document("_id", 3), new Document("_id", 3).append("x", 4)));

col.bulkWrite(writes);

col.drop();

col.bulkWrite(writes, new BulkWriteOptions().ordered(false));
//collection.find().forEach(printBlock);

// 删除数据库
db.drop();

6. GridFS文件上传

 1 GridFSBucket gridFSBucket = GridFSBuckets.create(db);
 2 File file = new File("D:/test.txt");
 3 if(!file.exists()) file.createNewFile();
 4 InputStream upload = new FileInputStream(file);
 5 ObjectId fileId = gridFSBucket.uploadFromStream("test.txt", upload);
 6 System.out.println("上传成功 fileID:" + fileId);
 7 
 8 // 查看上传的文件列表
 9 gridFSBucket.find().forEach(new Block<GridFSFile>() {
10     @Override
11     public void apply(final GridFSFile gridFSFile) {
12         System.out.println(gridFSFile.getFilename());
13     }
14 });
15 // 下载一个文件通过FileId
16 FileOutputStream streamToDownloadTo = new FileOutputStream("/tmp/test.txt");
17 gridFSBucket.downloadToStream(fileId, streamToDownloadTo);
18 streamToDownloadTo.close();
19 
20 // 通过文件名下载一个文件
21 streamToDownloadTo = new FileOutputStream("/tmp/test.txt");
22 GridFSDownloadByNameOptions downloadOptions = new GridFSDownloadByNameOptions().revision(0);
23 gridFSBucket.downloadToStreamByName("test.txt", streamToDownloadTo, downloadOptions);
24 streamToDownloadTo.close();
25 
26 // 根据FileId重命名和删除文件
27 gridFSBucket.rename(fileId, "test1.txt");
28 gridFSBucket.delete(fileId);

以上只是简单的操作,参考自官网的demo,下面是jar包下载地址和源码例子的链接,

驱动包下载:https://github.com/mongodb/mongo-java-driver/releases

源码demo:https://github.com/mongodb/mongo-java-driver/tree/master/driver/src/examples

MongoDB-Java

标签:

原文地址:http://www.cnblogs.com/cyhe/p/5451421.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!