Java实现对MongoDB的AND、OR和IN操作

8 篇文章 0 订阅
7 篇文章 0 订阅
       在MongoDB的官方文档中关于 Java操作的介绍,只给出了很简单的几个例子。这些例子虽然可以满足一定的需求,但是还并不是太完全。下面是我根据网页中的提示写的几个例子。

       1.背景。用JUnit4.8.2实现的单元测试的形式。测试数据:

{uid:10,username:"Jim",age:23,agender:"male"}
{uid:27,username:"tom",age:13,agender:"male"}
{uid:12,username:"Jane",age:31,agender:"female"}
{uid:23,username:"Alex",age:47,agender:"male"}
{uid:109,username:"Lily",age:24,agender:"female"}

      单元测试的初始化和清理工作,主要是建立数据库连接、写入测试数据、清理测试数据:

	private static List<BasicDBObject> documents = new ArrayList<BasicDBObject>();
	private static DBCollection coll;
	
	@BeforeClass
	public static void init(){
		try {
			
			initConnection();
			
			loadData();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static void initConnection() throws UnknownHostException, MongoException{
		//Create a connection to Collection 'user'
		Mongo mongo = new Mongo("localhost", 27017);
		DB db = mongo.getDB("test");
		coll = db.getCollection("user");
	}
	
	private static void loadData() throws Exception{
		BufferedReader br = new BufferedReader(new InputStreamReader(MongoTest.class.getResourceAsStream("data")));
		String line = null;
		while((line = br.readLine()) != null){
			JSONObject jo = new JSONObject(line);
			
			//Convert JSONObject into BasicDBObject
			BasicDBObject dbObject = new BasicDBObject();
			Iterator<String> joKeys = jo.keys();
			while(joKeys.hasNext()){
				String key = joKeys.next();
				dbObject.put(key, jo.get(key));
			}
			
			documents.add(dbObject);
		}
	}
	
	@Before
	public void setUp(){
		//Insert all data into MongoDB
		for(BasicDBObject bdo : documents){
			coll.insert(bdo);
		}
	}
	
	@After
	public void cleanUp(){
		//Drop the collection to remove all data.
		//Note: it's not recommended.
		coll.drop();
	}

            2. AND是比较简单的。

	@Test
	public void testAnd(){
		//agender='female' AND age > 27	
		DBObject queryCondition = new BasicDBObject();
		queryCondition.put("agender", "female");
		queryCondition.put("age", new BasicDBObject("$gt", 27));
		DBCursor dbCursor = coll.find(queryCondition);
		assertEquals(1, dbCursor.size());
		assertEquals("Jane", dbCursor.next().get("username"));
	}

           3.单个字段的OR操作。

	@Test
	public void testOrSingleField(){
		DBObject queryCondition = new BasicDBObject();		
		//age<15 OR age>27
		queryCondition = new BasicDBObject();
		BasicDBList values = new BasicDBList();
		values.add(new BasicDBObject("age", new BasicDBObject("$gt", 27)));
		values.add(new BasicDBObject("age", new BasicDBObject("$lt", 15)));
		queryCondition.put("$or", values);
		
		DBCursor dbCursor = coll.find(queryCondition);
		assertEquals(3, dbCursor.size());
		assertEquals("tom", dbCursor.next().get("username"));
	}

          4. 多个字段之间的OR操作

	@Test
	public void testOrMultiFields(){
		DBObject queryCondition = new BasicDBObject();		
		//agender=female OR age<=23
		queryCondition = new BasicDBObject();
		BasicDBList values = new BasicDBList();
		values.add(new BasicDBObject("agender", "female"));
		values.add(new BasicDBObject("age", new BasicDBObject("$lte", 23)));
		queryCondition.put("$or", values);
		
		DBCursor dbCursor = coll.find(queryCondition);
		assertEquals(4, dbCursor.size());
		assertEquals("Jim", dbCursor.next().get("username"));
	}

         5. 单个字段的IN操作。对于类似 where age=13 OR age=47的查询条件,就可以考虑使用IN代替

	@Test
	public void testIn(){
		DBObject queryCondition = new BasicDBObject();		
		//age in [13, 47]
		queryCondition = new BasicDBObject();
		BasicDBList values = new BasicDBList();
		values.add(13);
		values.add(47);
		queryCondition.put("age", new BasicDBObject("$in", values));
		
		DBCursor dbCursor = coll.find(queryCondition);
		assertEquals(2, dbCursor.size());
		assertEquals("tom", dbCursor.next().get("username"));
	}

         从以上几个例子可以看出,通过BasicDBList与BasicDBObject的相结合可以得出比较复杂的查询条件。




  • 6
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
Chapter 1, Why Should I Care for Test-Driven Development?, spells out our goal of becoming a Java developer with a TDD black belt. In order to know where we're going, we'll have to discuss and find answers to some questions that will define our voyage. Chapter 2, Tools, Frameworks, and Environments, will compare and set up all the tools, frameworks and environments that will be used throughout this book. Each of them will be accompanied with code that demonstrates their strengths and weaknesses. Chapter 3, Red-Green-Refactor – From Failure Through Success until Perfection, will help us develop a Tic-Tac-Toe game using the red-greenrefactor technique, which is the pillar of TDD. We'll write a test and see it fail; we'll write a code that implements that test, run all the tests, and see them succeed; and finally, we'll refactor the code and try to make it better. Chapter 4, Unit Testing – Focusing on What You Do and Not on What Has Been Done, shows that to demonstrate the power of TDD applied to unit testing, we'll need to develop a remote-controlled ship. We'll learn what unit testing really is, how it differs from functional and integration tests, and how it can be combined with test-driven development. Chapter 5, Design – If It's Not Testable, It's Not Designed Well, will help us develop a Connect 4 game without any tests and try to write tests at the end. This will give us insights into the difficulties we are facing when applications are not developed in a way that they can be tested easily. Chapter 6, Mocking – Removing External Dependencies, shows how TDD is about speed. We want to quickly demonstrate some idea/concept. We'll continue developing our Tic-Tac-Toe game by adding MongoDB as our data storage. None of our tests will actually use MongoDB since all communications to it will be mocked. Chapter 7, TDD and Functional Programming – A Perfect Match, dives into the functional programming paradigm and how TDD could be applied when programming in that way. We'
在使用Java语言实现MongoDB逻辑隔离时,可以通过创建多个数据库用户来实现。每个用户只能访问其所拥有的数据库,从而实现逻辑隔离。 具体步骤如下: 1. 在MongoDB中创建多个数据库,并为每个数据库分配不同的用户。 2. 在Java代码中,使用MongoClient连接到MongoDB,并使用不同的用户名和密码进行身份验证。 3. 在每个Java应用程序中,只使用与该应用程序相关的数据库用户进行操作。 4. 在代码中实现访问控制,确保每个用户只能访问其所拥有的数据库。 例如,以下代码演示了如何使用Java语言实现MongoDB逻辑隔离: ``` MongoClient mongoClient = new MongoClient("localhost", 27017); // 创建数据库用户 mongoClient.getDatabase("db1").createUser("user1", "password".toCharArray()); mongoClient.getDatabase("db2").createUser("user2", "password".toCharArray()); // 使用不同的用户名和密码连接到MongoDB MongoCredential credential1 = MongoCredential.createCredential("user1", "db1", "password".toCharArray()); MongoCredential credential2 = MongoCredential.createCredential("user2", "db2", "password".toCharArray()); // 在每个Java应用程序中,只使用与该应用程序相关的数据库用户进行操作 MongoDatabase db1 = mongoClient.getDatabase("db1").withCredential(credential1); MongoDatabase db2 = mongoClient.getDatabase("db2").withCredential(credential2); // 在代码中实现访问控制,确保每个用户只能访问其所拥有的数据库 MongoCollection<Document> collection1 = db1.getCollection("collection1"); MongoCollection<Document> collection2 = db2.getCollection("collection2"); ``` 通过以上步骤,就可以使用Java语言实现MongoDB的逻辑隔离。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mydeman

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值