使用Java操作mongodb

  |   0 评论   |   20 浏览

背景

初体验

pom

		<dependency>
			<groupId>org.mongodb</groupId>
			<artifactId>mongodb-driver</artifactId>
			<version>3.4.0</version>
		</dependency>

上传和下载文件

package testMongoDB;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.bson.Document;
import org.bson.types.ObjectId;

import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.mongodb.client.gridfs.model.GridFSUploadOptions;

public class MainUpload {

	public static void main(String[] args) throws Exception {
		// 连接 MongoDB
		MongoClientOptions mongoClientOptions = MongoClientOptions.builder().build();
		ServerAddress serverAddress = new ServerAddress("localhost", 27017);
		MongoClient mongoClient = new MongoClient(serverAddress, mongoClientOptions);
		MongoDatabase mongoDatabase = mongoClient.getDatabase("test");

		/*
		 * MongoDB 会生成两个collections(fs.chunks和fs.files) fs.files存放文件信息
		 * fs.chunks存放文件的二进制流
		 */
		GridFSBucket bucket = GridFSBuckets.create(mongoDatabase, "fs");

		// 上传文件
		File file = new File("/tmp/bug.log");
		InputStream inputStream = new FileInputStream(file);

		Document document = new Document();
		document.put("from", "abeffect");

		// metadata方法可以为文件上传的同时附加一些元数据
		GridFSUploadOptions gridFSUploadOptions = new GridFSUploadOptions().chunkSizeBytes(358400).metadata(document);
		ObjectId id = bucket.uploadFromStream("bug.log", inputStream, gridFSUploadOptions);
		System.out.println("objectid=" + id);

		// 遍历文件
		bucket.find().forEach(new Block<GridFSFile>() {
			@Override
			public void apply(GridFSFile file) {
				System.out.println(file);
			}
		});

		// 下载文件
		bucket.downloadToStream("bug.log", new FileOutputStream(new File("/tmp/bug2.log")));

		mongoClient.close();
	}
}

读写二进制数据

package testMongoDB;

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class MainUploadBinary {

	public static void main(String[] args) throws Exception {
		// 连接 MongoDB
		MongoClientOptions mongoClientOptions = MongoClientOptions.builder().build();
		ServerAddress serverAddress = new ServerAddress("localhost", 27017);
		MongoClient mongoClient = new MongoClient(serverAddress, mongoClientOptions);
		MongoDatabase mongoDatabase = mongoClient.getDatabase("test");

		// 找到 collection
		mongoDatabase.createCollection("test");
		MongoCollection<Document> collection = mongoDatabase.getCollection("test");

		// 写数据
		Document document = new Document("from", "abeffect").append("author", "note").append("value", "100");
		document.append("data", "hello world".getBytes());
		List<Document> documents = new ArrayList<Document>();
		documents.add(document);
		collection.insertMany(documents);

		// 遍历数据
		FindIterable<Document> findIterable = collection.find();
		MongoCursor<Document> mongoCursor = findIterable.iterator();
		while (mongoCursor.hasNext()) {
			System.out.println(mongoCursor.next());
		}

		// 更新数据 将 value = 100 改为 value = 200
		collection.updateMany(Filters.eq("value", 100), new Document("$set", new Document("value", 200)));

		// 删除一条匹配的数据
		collection.deleteOne(Filters.eq("value", 200));

		// 删除所有匹配的数据
		collection.deleteMany(Filters.eq("value", 200));

		// 删除数据表
		collection.drop();
		mongoClient.close();
	}
}

评论

发表评论