1. 程式人生 > >java操作mongo的and,or, in操作

java操作mongo的and,or, in操作

</pre><pre name="code" class="java">public static void main(String[] args) throws IOException {
		MechineLog log = new MechineLog();

		MongoTemplate mt = log.getMongoTemplate("");

		DB db = log.getDb("", "mydb");
		// DBCollection coll = db.getCollection("mytable2");
		DBCollection coll = db.getCollection("log_20141107");
		// DBCursor cursor = coll.find();
		// List<DBObject> list = cursor.toArray();
		//
		// System.out.println(list);
		// if (cursor.hasNext()) {
		// DBObject dbObject = cursor.next();
		// // for (String key : dbObject.keySet()) {
		// // System.out.println(key + ": " + dbObject.get(key));
		// // }
		// Map<String, DeviceLog> map = dbObject.toMap();
		// System.out.println(map);
		// // }
		List<DBObject> list = null;
		// List<DBObject> list = coll.find(new BasicDBObject("name", "a"))
		// .toArray();

		// list = coll.find(null, new BasicDBObject("age", true), 0,
		// 25).toArray();
		// for (DBObject o : list) {
		// System.out.println(o);
		// }
                
                in(coll);

 }

	// in操作 age in(10,30)
	private static void in(DBCollection coll) {
		List<DBObject> list;
		BasicDBObject query = new BasicDBObject();
		BasicDBList values = new BasicDBList();
		values.add(10);
		values.add(30);
		query.append("age", new BasicDBObject("$in", values));
		list = coll.find(query).toArray();
		for (DBObject o : list) {
			System.out.println(o);
		}
	}

	private static void multiOr(DBCollection coll) {
		List<DBObject> list;
		// 多個欄位or操作 name='a' or age>30;
		BasicDBObject query = new BasicDBObject();
		BasicDBList values = new BasicDBList();
		values.add(new BasicDBObject("name", "a"));
		values.add(new BasicDBObject("age", new BasicDBObject("$gt", 30)));
		query.put("$or", values);
		list = coll.find(query).toArray();
		for (DBObject o : list) {
			System.out.println(o);
		}
	}

	// 單個欄位or操作 age<20 or age>=30
	private static void singOr(DBCollection coll) {
		List<DBObject> list;
		BasicDBObject query = new BasicDBObject();
		BasicDBList values = new BasicDBList();
		values.add(new BasicDBObject("age", new BasicDBObject("$gte", 30)));
		values.add(new BasicDBObject("age", new BasicDBObject("$lt", 20)));
		query.put("$or", values);
		list = coll.find(query).toArray();
		for (DBObject o : list) {
			System.out.println(o);
		}
	}

	// 'and' operate
	private static void and(DBCollection coll) {
		List<DBObject> list;
		BasicDBObject dbObject = new BasicDBObject();
		dbObject.put("name", "a");
		dbObject.put("age", new BasicDBObject("$gt", 10));
		list = coll.find(dbObject).toArray();
		for (DBObject o : list) {
			System.out.println(o);
		}
	}