Java操作MongoDB简单demo以及操作配置文件demo

1、请先参考我的上一篇https://blog.csdn.net/qq_37575994/article/details/84484782

2、https://github.com/mongodb/mongo-java-driver下载需要的jar包【Mongodb-java=driver】,一般简单用法以下:

连接

MongoClient mongoClient=new MongoClient("localhost",27017);//获取MongoDB连接,端口号27017
MongoDatabase mongoDatabase=mongoClient.getDatabase(“lp_test”);
MongoCollection<Document> collection = mongoDatabase.getCollection(“lp_test”);//获取数据库lp_test下的集合lp_test,如果没有将自动创建

插入

如:

collection.insertOne(document);//单条

collection.insertMany(documents);//多条

查询

过滤条件函数
collection().find().eq(fieldName,value);//等于
collection().find().gt(fieldName,value);//大于
collection().find().lt(fieldName,value);//小于
collection().find().gte(fieldName,value);
collection().find().lte(fieldName,value);
collection().find().exists(fieldName);

排序操作

对FindIterable对象使用sort函数进行排序。ascending函数表示升序,descending函数表示降序。

collection.find().sort(orderBy(ascending("x", "y"), descending("z")));

过滤字段

并不需要一条数据中所有的内容,只需要一部分,使用projection方法。

如:collection.find().projection(fields(include("x", "y"), excludeId()));

单条更新

第一个参数选取需要被更新的记录,第二个参数设置需要被更新的具体数据。

如:collection.updateOne(eq("name", 456), new Document("$set", new Document("title", "hi")));

多条更新

如:

UpdateResult updateResult = collection.updateMany(lt("_id", 100), new Document("$inc", new Document("name", "lplplp")));//保存了数据更新的结果

删除数据

如:

collection.deleteOne(eq("_id", 110)); //单条

DeleteResult deleteResult = collection.deleteMany(gte("_id", 100));//多条

部分的可运行简单实例:

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

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

import static com.mongodb.client.model.Filters.*;

public class MongoDBJDBC {
	public static void main(String[] args) {
		
		MongoCollection<Document> collection=get_collection("lp_test","lp_test");
		
		//insert_one(collection,new Document().append("日期","11月26日下午").append("what","我在集合里面的文档又加了一个").append("这是一个内嵌文档", new Document("city", "NC").append("x", 1).append("y","2")));
		
		/*List<Document> documents=new ArrayList<Document>();
		documents.add(new Document().append("how","没什么"));
		documents.add(new Document().append("where","江西").append("123",true));
		documents.add(new Document().append("where","江西").append("321",new Document().append("how","没什么")));
		insert_many(collection,documents);*/
		
		
		//System.out.println(find_one(collection).toString());
		//System.out.println(find_many(collection).toString());
		
		/*
		Document myDoc = collection.find(eq("name", 456)).first();
		System.out.println(myDoc);
		*/
		
	}

	/***
	 * 获取一个数据库连接,返回特有文档集合
	 * @param dataBase
	 * @param collecTion
	 * @return
	 */
	public static  MongoCollection<Document>  get_collection(String dataBase,String collecTion){
		MongoCollection<Document> collection = null;
		try{
			@SuppressWarnings("resource")
			MongoClient mongoClient=new MongoClient("localhost",27017);//获取MongoDB连接,端口号27017
			MongoDatabase mongoDatabase=mongoClient.getDatabase(dataBase);
			collection = mongoDatabase.getCollection(collecTion);//获取数据库dataBase下的集合collecTion,如果没有将自动创建
			System.out.println("成功获取"+dataBase+"数据库下的"+collecTion+"集合");
		}catch(Exception e){
			System.out.println("请打开MongoDB服务");
		}
		return collection;
	}
	/***
	 * 插入一条文档
	 * @param collection
	 * @param document
	 */
	public static void  insert_one(MongoCollection<Document> collection,Document document){
		collection.insertOne(document);
		System.out.println("一条文档成功添加!");
	}
	/**
	 * 插入多条文档
	 * @param collection
	 * @param documents
	 */
	public static void insert_many(MongoCollection<Document> collection,List<Document> documents){
		collection.insertMany(documents);
		System.out.println("多条文档成功添加!");
	}
	/***
	 * 返回查到的第一条文档,无条件
	 * @param collection
	 * @return
	 */
	public static Document find_one(MongoCollection<Document> collection){
		
		return collection.find().first();
	}
	/***
	 * 返回查询到的所有文档,无条件
	 * @param collection
	 * @return
	 */
	public static List<Document> find_many(MongoCollection<Document> collection){
		List<Document> documents=new ArrayList<Document>();
		MongoCursor<Document> cursor = collection.find().iterator();
		try {
		    while (cursor.hasNext()) {
		    	documents.add(cursor.next());
		    }
		} finally {
		    cursor.close();
		}
		return documents;
	}
	
	
}

Bulk操作

//有序
collection.bulkWrite(
  Arrays.asList(new InsertOneModel<>(new Document("_id", 1)),
                new InsertOneModel<>(new Document("_id", 2)),
                new UpdateOneModel<>(new Document("_id", 1),new Document("$set", new Document("name","hi"))),
                new DeleteOneModel<>(new Document("_id", 2)),
                new ReplaceOneModel<>(new Document("_id", 2),new Document("_id", 6).append("name", "lp"))));

//无序
collection.bulkWrite(
  Arrays.asList(new InsertOneModel<>(new Document("_id", 1)),
                new InsertOneModel<>(new Document("_id", 2)),
                new UpdateOneModel<>(new Document("_id", 1),new Document("$set", new Document("name", "hi"))),
                new DeleteOneModel<>(new Document("_id", 2)),
                new ReplaceOneModel<>(new Document("_id", 2),new Document("_id", 3).append("x", 4))),
  new BulkWriteOptions().ordered(false));

3、说实话上面的代码写得不好,本来就是链式函数,算了,凑合看吧,因为执行了很多方法就自己注释或者写得乱七八糟了,意会一下。

4、公共文件配置的使用

a、请注意将mongo-config.properties放置在项目的src目录下,该mongo-config.properties文件内容如下(以下内容可直接复制,参数自行修改):

connectionsPerHost=10
connectTimeout=10000
cursorFinalizerEnabled=true
maxWaitTime=120000
threadsAllowedToBlockForConnectionMultiplier=5
readSecondary=false
socketTimeout=0
socketKeepAlive=false
write=0
writeTimeout=0
journal=false
hostConfString=127.0.0.1:27017

b、配置文件工具类代码:

package prop;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import com.mongodb.*;
import com.mongodb.MongoClientOptions.Builder;

public class MongoDBUtil {
	
	public static MongoClient initMongo() throws IOException{
		InputStream inputStream=MongoDBUtil.class.getClassLoader().getResourceAsStream("mongo-config.properties");
		Properties prop=new Properties();
		prop.load(inputStream);
		WriteConcern concern=new WriteConcern(Integer.valueOf(prop.getProperty("write")),Integer.valueOf(prop.getProperty("writeTimeout")));//读取WriteConcern对象的参数write和、writeTimeout值
		concern.withJournal(Boolean.valueOf(prop.getProperty("journal")));//读取journal参数值
		//疯狂读取参数
		Builder builder=MongoClientOptions.builder().connectionsPerHost(Integer.valueOf(prop.getProperty("connectionsPerHost"))).connectTimeout(Integer.valueOf(prop.getProperty("connectTimeout"))).cursorFinalizerEnabled(Boolean.valueOf(prop.getProperty("cursorFinalizerEnabled"))).maxWaitTime(Integer.valueOf(prop.getProperty("maxWaitTime"))).threadsAllowedToBlockForConnectionMultiplier(Integer.valueOf(prop.getProperty("threadsAllowedToBlockForConnectionMultiplier"))).socketTimeout(Integer.valueOf(prop.getProperty("socketTimeout"))).socketKeepAlive(Boolean.valueOf(prop.getProperty("socketTimeout"))).writeConcern(concern);
		if(Boolean.valueOf(prop.getProperty("readSecondary"))){//读取readSecondary参数值并判断
			builder.readPreference(ReadPreference.secondaryPreferred());
		}
		String[] address=prop.getProperty("hostConfString").split(":");//读取服务IP地址和端口号
		ServerAddress serverAddress=new ServerAddress(address[0],Integer.valueOf(address[1]));
		//把设置的结果返回调用的主程序
		return new MongoClient(serverAddress,builder.build());
		}
}

c、以上两个文件我进行了一下测试,代码如下:

package prop;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.bson.Document;
import org.junit.Before;
import org.junit.Test;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

import static com.mongodb.client.model.Filters.*;

public class TestProp {

	private MongoClient mongoClient;
	@Before//在方法之前执行数据库初始化
	public void initMongoClient() throws IOException{
		
			mongoClient=MongoDBUtil.initMongo();//使用配置文件实现数据库连接	
			
	}
	@Test
	public void test() throws Exception{
		//找到数据库,如果没有就创建
		MongoDatabase db=mongoClient.getDatabase("prop_test");
		//找到数据库下的集合,如果没有就创建
		MongoCollection<Document> prop_1=db.getCollection("test1");
		
		//插入一条文档
		prop_1.insertOne(new Document().append("你好","hello"));
		//插入多条文档
		List<Document> documents=new ArrayList<Document>();
		documents.add(new Document().append("how","丑东西"));
		documents.add(new Document().append("address","江西").append("123",true));
		prop_1.insertMany(documents);
		//打印信息
		MongoCursor<Document> cursor1 = prop_1.find().iterator();
		try {
		    while (cursor1.hasNext()) {
		    	System.out.print(cursor1.next());
		    }
		} finally {
		    cursor1.close();
		}
		System.out.println();
		//删除一条文档,包含键名为123
		prop_1.deleteOne(exists("123"));
		
		//打印信息
				MongoCursor<Document> cursor2 = prop_1.find().iterator();
				try {
				    while (cursor2.hasNext()) {
				    	System.out.print(cursor2.next());
				    }
				} finally {
				    cursor2.close();
				}
		//关闭资源
		mongoClient.close();
	
	}

}

以上代码我的本地测试运行完全OK,可以直接粘贴使用!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值