`

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

 
阅读更多

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的相结合可以得出比较复杂的查询条件。

 

转自:http://blog.csdn.net/mydeman/article/details/6652387

分享到:
评论

相关推荐

    Mongodb in Mycat指南

    ### MongoDB in Mycat 指南 ...通过上述配置和实现方式,Mycat能够有效地支持MongoDB的接入,并且提供了一套相对完整的SQL语法支持机制。这对于需要处理大量非结构化数据的应用来说,是非常有价值的。

    MongoDB Cookbook 2nd 2016第2版 无水印pdf 0分

    You do not need any prior knowledge of MongoDB, but it would be helpful if you have some programming experience in either Java or Python. What You Will Learn Install, configure, and administer ...

    MongoDB常用的查询更新等操作汇总

    在本文中,我们将深入探讨一些MongoDB常用的操作,包括查询、更新和其他高级特性。 1. **查询操作**: - `find` 方法用于执行查询。例如,`db.collection_name.find()` 返回集合中的所有文档。 - 要指定返回的...

    Pentaho Analytics for MongoDB Cookbook(PACKT,2015)

    The variant features in Pentaho for MongoDB are designed to empower organizations to be more agile and scalable and also enables applications to have better flexibility, faster performance, and lower...

    mongo2SQL:Mongodb 查询到 sql 查询转换器

    Mongodb 查询到 sql 查询转换器。 示例:在:db.user.find({name: 'julio'})... 翻译器支持以下 mongodb 操作符: $or $and (记住 $and 和对象上的逗号分隔值是相同的) $lt $lte $gt $gte $ne $in 输入文件:input_

    Pro Couchbase Development(Apress,2015)

    This book is for big data developers who use Couchbase NoSQL database or want to use Couchbase for their web applications as well as for those migrating from other NoSQL databases like MongoDB and ...

    SQL语句最优化

    同时,还涉及了使用AND、OR和IN条件来组合查询文档,以及find()方法中投影(projection)的使用。 6. MongoDB的聚合操作:聚合是MongoDB中一个强大的特性,用于处理集合中的数据,执行一系列的转换和分析工作。文件...

    test-driven-java-development-2nd2018

    provided by Java since version 8 and create readable and meaningful tests. Chapter 8, BDD – Working Together with the Whole Team, discusses developing a book store application by using the BDD ...

    Beginning Spring 5: From Novice to Professional

    You’ll see how Spring has drastically and positively affected the way we program and design applications in Java. Beginning Spring 5 discusses how you can build apps with the Spring mindset and ...

    8天学会nosql

    还可以使用 `find()` 方法进行复杂查询,如 AND (`$and`), OR (`$or`), IN (`$in`), NOT IN (`$nin`) 等逻辑组合。 3. **改(Update)**: `update()` 方法用于更新数据,其参数包括查找条件和更新值。例如,`db....

    Learning.Node.js.for..NET.Developers.epub

    This short guide will help you develop applications using JavaScript and Node.js, leverage your existing programming skills from .NET or Java, and make the most of these other platforms through ...

    Beginning Hibernate, 3rd Edition

    Third Edition is ideal if you’re experienced in Java with databases (the traditional, or «connected,» approach), but new to open-source, lightweight Hibernate, a leading object-relational mapping ...

    mongo中模糊查询使用和QueryOperators宣贯.pdf

    在MongoDB中,模糊查询和QueryOperators是两个关键概念,用于实现更复杂的查询操作。MongoDB是一个基于分布式文件存储的NoSQL数据库系统,它提供了丰富的查询语言,支持多种数据模型,包括文档、图形和键值对。本文...

    camel-manual-2.0

    There are multiple ways to add routes and configure Camel, including using Spring or directly in Java, as shown in the example above. #### Architecture The architecture of Apache Camel is centered ...

    MongoDB数据查询方法干货篇

    此外,MongoDB 还支持更复杂的查询操作,如范围查询、正则表达式查询、逻辑运算符($or、$and 等)、数组查询等。例如,查询年龄在 20 至 30 之间的用户: ```javascript db.user.find({age: {$gte: 20, $lte: 30}}...

Global site tag (gtag.js) - Google Analytics