MongoDB_Java連線mongo 使用Java多條件查詢mongo資料
阿新 • • 發佈:2018-12-24
在mongo shell中的查詢語句是這樣的..
db.user.find({"age":{"$gt":5,"$lt":14}})
我們用Java連線mongo來實現.
mongo庫中的資料
程式碼
查詢結果package com.java.module.mongo.mongo_test_1; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MongoClient; /** * Java多條件查詢mongo */ public class JavaManyConditionsQuery { public static void main(String[] args) { try { MongoClient mongoClient = new MongoClient("192.168.125.125", 27017); DB db = mongoClient.getDB("test"); DBCollection dbCollection = db.getCollection("user"); //將兩個並聯的查詢條件放入一個裡面. DBObject dbQuery = new BasicDBObject(); dbQuery.put("$gt", 5); dbQuery.put("$lt", 14); DBObject query = new BasicDBObject("age",dbQuery); DBCursor dbCursor = dbCollection.find(query); while (dbCursor.hasNext()) { System.out.println(dbCursor.next()); } } catch (Exception e) { e.printStackTrace(); } } }