① 高手幫幫忙,我剛接觸mongodb,怎麼用java對mongodb資料庫進行多條件查詢,先謝謝了
package maven.demo.test;
import java.util.ArrayList;
import java.util.List;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.QueryOperators;
public class MongoDB {
private static void print(String str){
System.out.println(str);
}
public static void main(String[] args) {
try {
//創建連接
Mongo m=new Mongo("127.0.0.1", 27017);
//得到資料庫
DB db=m.getDB("test");
//得到所有資料庫
// List<String> colls=m.getDatabaseNames();
// for(String str:colls){
// System.out.println(str);
// }
// //得到所有的集合(表)
// for(String collection:db.getCollectionNames()){
// System.out.println(collection);
// }
//刪除一個資料庫
//m.dropDatabase("sun");
//得到sun表
DBCollection coll=db.getCollection("things");
//查看一個表的索引
// for(DBObject index:coll.getIndexInfo()){
// System.out.println(index);
// }
// DBObject myDoc=coll.findOne();
// System.out.println(myDoc);
//添加
// BasicDBObject doc=new BasicDBObject();
// doc.put("name", "sunshan");
// doc.put("sex", "男");
// doc.put("age", 22);
//coll.insert(doc);
//刪除
//coll.remove(doc);
// BasicDBObject doc1=new BasicDBObject();
// doc1.put("i", 0);
// doc1.put("j", "foo");
// BasicDBObject doc2=new BasicDBObject();
// doc2.put("hello", "world");
// doc1.put("doc2", doc2);
// coll.insert(doc1);
//修改
// BasicDBObject doc3=new BasicDBObject();
// doc3.put("x", 6);
// BasicDBObject doc4=new BasicDBObject();
// doc4.put("x", 1);
// coll.update(doc3, doc4,true,false);
//如果資料庫不存在就添加 |多條修改 false只修改第一天,true如果有多條就不修改
//條件查詢
//System.out.println(coll.find(doc4));
//coll.findAndRemove(doc4);
// //批量插入
// List<DBObject> datas=new ArrayList<DBObject>();
// for(int i=0;i<10;i++){
// BasicDBObject bd=new BasicDBObject();
// bd.put("name", "data");
// bd.append("age", i);
// datas.add(bd);
// }
// coll.insert(datas);
//添加
// BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start();
// documentBuilder.add("database", "mkyongDB");
// documentBuilder.add("table", "hosting");
// BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start();
// documentBuilderDetail.add("records", "99");
// documentBuilderDetail.add("index", "vps_index1");
// documentBuilderDetail.add("active", "true");
// documentBuilder.add("detail", documentBuilderDetail.get());
// coll.insert(documentBuilder.get());
//添加
// Map<Object,Object> map=new HashMap<Object,Object>();
// map.put("a", 1);
// map.put("b", "b");
// coll.insert(new BasicDBObject(map));
//添加
// String json ="{'1' : '1','2' : '2',"+"'11' : {'1' : 1, '2' : '2', '3' : '3'}}";
// DBObject dbobject=(DBObject)JSON.parse(json);
// coll.insert(dbobject);
//更新
// BasicDBObject bdo=new BasicDBObject();
// bdo.put("x", 11);
// coll.update(new BasicDBObject().append("x", 0), bdo);
//更新
// BasicDBObject bdo=new BasicDBObject().append("$inc", new BasicDBObject().append("x", 12));
// coll.update(new BasicDBObject().append("x", 11), bdo);
//更新
//如果不使用$set 直接是 age則所有的都會更新
//根據age為9條件把name:data修改為 name:sun
// BasicDBObject bdo=new BasicDBObject().append("$set", new BasicDBObject().append("name", "sunshan"));
// coll.update(new BasicDBObject().append("age", 9), bdo);
//更新
//根據name為data條件把age:批量修改為 age:age
// BasicDBObject bdo=new BasicDBObject().append("$set", new BasicDBObject().append("age", "age"));
// coll.update(new BasicDBObject().append("name", "data"), bdo,false, true);
//查詢age=1
// print("find:"+coll.find(new BasicDBObject("age", 1)).toArray());
//查詢age<=1
// print("find: "+coll.find(new BasicDBObject("age", new BasicDBObject("$lte", 1))).toArray());
//查詢age>=1
// print("fint: "+coll.find(new BasicDBObject("age", new BasicDBObject("$gte", 1))).toArray());
//查詢age!=1
// print("fint: "+coll.find(new BasicDBObject("age", new BasicDBObject("$ne", 1))).toArray());
//查詢age=1,2,3
// print("fint: "+coll.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.IN ,new int[]{1,2,3}))).toArray());
//查詢age!=1,2,3
// print("find: "+coll.find(new BasicDBObject("age" ,new BasicDBObject(QueryOperators.NIN ,new int[]{1,2,3}))).toArray());
// print("find: "+coll.find(new BasicDBObject("age" ,new BasicDBObject(QueryOperators.EXISTS ,true))).toArray());
//查詢age屬性
// print("find: "+coll.find(null ,new BasicDBObject("age" ,true)).toArray());
// List<DBObject> list=coll.find().toArray();
// for(Object obj:list){
// System.out.println(obj);
// }
//true查詢出來存在的 /false 查詢出來不存在的
//print(""+coll.find(new BasicDBObject("y",new BasicDBObject(QueryOperators.EXISTS,false))).toArray());
// DBObject dbc=new BasicDBObject();
// dbc.put("name", 1111);
// List<DBObject> list=new ArrayList<DBObject>();
// list.add(dbc);
// System.out.println(coll.insert(list).getN());
// //查詢部分數據塊
// DBCursor cursor=coll.find().skip(1);
// while(cursor.hasNext()){
// System.out.println(cursor.next());
// }
// DBCursor cur=coll.find(); //DBCursor cur=coll.find().limit(2);
// while(cur.hasNext()){
// System.out.println(cur.next());
// }
//System.out.println(cur.getCursorId()+" "+cur.count()+" "+JSON.serialize(cur));
//條件查詢
BasicDBObject doc5=new BasicDBObject();
doc5.put("$gt", 1);
doc5.put("$lt", 3);
print("find 21<y<23:"+coll.find(new BasicDBObject("y", doc5)).toArray());
// BasicDBObject doc5=new BasicDBObject();
// doc5.put("$gt", 1);
// doc5.put("$lt", 3);
// BasicDBObject doc6=new BasicDBObject();
// doc6.put("x", doc5);
// System.out.println(coll.find(doc6));
} catch (Exception e) {
e.printStackTrace();
}
}
}
② java怎麼做到使用mongodb來進行分組查詢統
java操作mongodb進行查詢,常用篩選條件的設置如下:
條件列表:
BasicDBList condList = new BasicDBList();
臨時條件對象:
BasicDBObject cond = null;
DBCollection coll = db.getCollection("A");
1、$where
在某種應用場合,若要集合A查詢文檔且要滿足文檔中某些屬性運算結果,可以編寫一腳本函數用where進行設置,比如:
某集合中存放的用戶信息,包括姓名、年齡、手機號、地址等,要篩選出年齡大於20且小於等於40的用戶,我們可以這樣:
String ageStr = "function (){return parseFloat(this.age) > 20 && parseFloat(this.age) <= 40};";
cond = new BasicDBObject();
cond.put("$where",ageStr);
放入條件列表
condList.add(cond);
2、$in
接1實例中,要查詢年齡為23、40、50的用戶信息,我們可以這樣:
創建一個臨時的條件列表對象,將條件值分別添加進去
BasicDBList values = new BasicDBList();
values.add(23);
values.add(40);
values.add(50);
cond = new BasicDBObject();
cond.put("age",new BasicDBObject("$in",values));
放入條件列表
condList.add(cond);
3、模糊匹配
接1實例中,要按照用戶的姓名進行模糊查詢,如:王,我們可以這樣做:
使用不區分大小寫的模糊查詢
3.1完全匹配
③ 如何用Java操作MongoDB
HelloWorld程序
學習任何程序的第一步,都是編寫HelloWorld程序,我們也不例外,看下如何通過Java編寫一個HelloWorld的程序。
首先,要通過Java操作Mongodb,必須先下載Mongodb的Java驅動程序,可以在這里下載。
新建立一個Java工程,將下載的驅動程序放在庫文件路徑下,程序代碼如下:
packagecom.mkyong.core;
importjava.net.UnknownHostException;
importcom.mongodb.BasicDBObject;
importcom.mongodb.DB;
importcom.mongodb.DBCollection;
importcom.mongodb.DBCursor;
importcom.mongodb.Mongo;
importcom.mongodb.MongoException;
/**
*Java+MongoDBHelloworldExample
*
*/
publicclassApp{
publicstaticvoidmain(String[]args){
try{
//實例化Mongo對象,連接27017埠
Mongomongo=newMongo("localhost",27017);
//連接名為yourdb的資料庫,假如資料庫不存在的話,mongodb會自動建立
DBdb=mongo.getDB("yourdb");
//GetcollectionfromMongoDB,databasenamed"yourDB"
//從Mongodb中獲得名為yourColleection的數據集合,如果該數據集合不存在,Mongodb會為其新建立
DBCollectioncollection=db.getCollection("yourCollection");
//使用BasicDBObject對象創建一個mongodb的document,並給予賦值。
BasicDBObjectdocument=newBasicDBObject();
document.put("id",1001);
document.put("msg","helloworldmongoDBinJava");
//將新建立的document保存到collection中去
collection.insert(document);
//創建要查詢的document
BasicDBObjectsearchQuery=newBasicDBObject();
searchQuery.put("id",1001);
//使用collection的find方法查找document
DBCursorcursor=collection.find(searchQuery);
//循環輸出結果
while(cursor.hasNext()){
System.out.println(cursor.next());
}
System.out.println("Done");
}catch(UnknownHostExceptione){
e.printStackTrace();
}catch(MongoExceptione){
e.printStackTrace();
}
}
}
最後,輸出的結果為:
{"_id":{"$oid":"4dbe5596dceace565d229dc3"},
"id":1001,"msg":"helloworldmongoDBinJava"}
Done
在上面的例子中,演示了使用Java對Mongodb操作的重要方法和步驟,首先通過創建Mongodb對象,傳入構造函數的參數是Mongodb的資料庫所在地址和埠,然後使用
getDB方法獲得要連接的資料庫名,使用getCollection獲得數據集合的名,然後通過新建立BasicDBObject對象去建立document,最後通過collection的insert方法,將建立的document保存到資料庫中去。而collection的find方法,則是用來在資料庫中查找document。
從Mongodb中獲得collection數據集
在Mongodb中,可以通過如下方法獲得資料庫中的collection:
DBCollectioncollection=db.getCollection("yourCollection");
如果你不知道collection的名稱,可以使用db.getCollectionNames()獲得集合,然後再遍歷,如下:
DBdb=mongo.getDB("yourdb");
Setcollections=db.getCollectionNames();
for(StringcollectionName:collections){
System.out.println(collectionName);
}
完成的一個例子如下:
packagecom.mkyong.core;
importjava.net.UnknownHostException;
importjava.util.Set;
importcom.mongodb.DB;
importcom.mongodb.DBCollection;
importcom.mongodb.Mongo;
importcom.mongodb.MongoException;
/**
*Java:GetcollectionfromMongoDB
*
*/
publicclassGetCollectionApp{
publicstaticvoidmain(String[]args){
try{
Mongomongo=newMongo("localhost",27017);
DBdb=mongo.getDB("yourdb");
Set<String>collections=db.getCollectionNames();
for(StringcollectionName:collections){
System.out.println(collectionName);
}
DBCollectioncollection=db.getCollection("yourCollection");
System.out.println(collection.toString());
System.out.println("Done");
}catch(UnknownHostExceptione){
e.printStackTrace();
}catch(MongoExceptione){
e.printStackTrace();
}
}
}
Mongodb中如何插入數據
下面,講解下如何使用4種方式,將JSON數據插入到Mongodb中去。首先我們准備JSON
格式的數據,如下:
{
"database":"mkyongDB",
"table":"hosting",
"detail":
{
records:99,
index:"vps_index1",
active:"true"
}
}
}
我們希望用不同的方式,通過JAVA代碼向Mongodb插入以上格式的JSON數據
第一種方法,是使用BasicDBObject,方法如下代碼所示:
BasicDBObjectdocument=newBasicDBObject();
document.put("database","mkyongDB");
document.put("table","hosting");
BasicDBObjectdocumentDetail=newBasicDBObject();
documentDetail.put("records","99");
documentDetail.put("index","vps_index1");
documentDetail.put("active","true");
document.put("detail",documentDetail);
collection.insert(document);
第二種方法是使用BasicDBObjectBuilder對象,如下代碼所示:
=BasicDBObjectBuilder.start()
.add("database","mkyongDB")
.add("table","hosting");
Detail=BasicDBObjectBuilder.start()
.add("records","99")
.add("index","vps_index1")
.add("active","true");
documentBuilder.add("detail",documentBuilderDetail.get());
collection.insert(documentBuilder.get());
第三種方法是使用Map對象,代碼如下:
MapdocumentMap=newHashMap();
documentMap.put("database","mkyongDB");
documentMap.put("table","hosting");
MapdocumentMapDetail=newHashMap();
documentMapDetail.put("records","99");
documentMapDetail.put("index","vps_index1");
documentMapDetail.put("active","true");
documentMap.put("detail",documentMapDetail);
collection.insert(newBasicDBObject(documentMap));
第四種方法,也就是最簡單的,即直接插入JSON格式數據
String json="{'database' : 'mkyongDB','table' : 'hosting',"+
"'detail' : {'records' : 99, 'index' : 'vps_index1', 'active' : 'true'}}}";
DBObject dbObject=(DBObject)JSON.parse(json);
collection.insert(dbObject);
這里使用了JSON的parse方法,將解析後的JSON字元串轉變為DBObject對象後再直接插入到collection中去。
完整的代碼如下所示:
packagecom.mkyong.core;
importjava.net.UnknownHostException;
importjava.util.HashMap;
importjava.util.Map;
importcom.mongodb.BasicDBObject;
importcom.mongodb.BasicDBObjectBuilder;
importcom.mongodb.DB;
importcom.mongodb.DBCollection;
importcom.mongodb.DBCursor;
importcom.mongodb.DBObject;
importcom.mongodb.Mongo;
importcom.mongodb.MongoException;
importcom.mongodb.util.JSON;
/**
* Java MongoDB : Insert a Document
*
*/
publicclass InsertDocumentApp {
publicstaticvoid main(String[] args){
try{
Mongo mongo=newMongo("localhost",27017);
DB db=mongo.getDB("yourdb");
//get a single collection
DBCollection collection=db.getCollection("mmyColl");
//BasicDBObject example
System.out.println("BasicDBObject example...");
BasicDBObject document=newBasicDBObject();
document.put("database","mkyongDB");
document.put("table","hosting");
BasicDBObject documentDetail=newBasicDBObject();
documentDetail.put("records","99");
documentDetail.put("index","vps_index1");
documentDetail.put("active","true");
document.put("detail", documentDetail);
collection.insert(document);
DBCursor cursorDoc=collection.find();
while(cursorDoc.hasNext()){
System.out.println(cursorDoc.next());
}
collection.remove(newBasicDBObject());
//BasicDBObjectBuilder example
System.out.println("BasicDBObjectBuilder example...");
BasicDBObjectBuilder documentBuilder=BasicDBObjectBuilder.start()
.add("database","mkyongDB")
.add("table","hosting");
BasicDBObjectBuilder documentBuilderDetail=BasicDBObjectBuilder.start()
.add("records","99")
.add("index","vps_index1")
.add("active","true");
documentBuilder.add("detail", documentBuilderDetail.get());
collection.insert(documentBuilder.get());
DBCursor cursorDocBuilder=collection.find();
while(cursorDocBuilder.hasNext()){
System.out.println(cursorDocBuilder.next());
}
collection.remove(newBasicDBObject());
//Map example
System.out.println("Map example...");
Map documentMap=newHashMap();
documentMap.put("database","mkyongDB");
documentMap.put("table","hosting");
Map documentMapDetail=newHashMap();
documentMapDetail.put("records","99");
documentMapDetail.put("index","vps_index1");
documentMapDetail.put("active","true");
documentMap.put("detail", documentMapDetail);
collection.insert(newBasicDBObject(documentMap));
DBCursor cursorDocMap=collection.find();
while(cursorDocMap.hasNext()){
System.out.println(cursorDocMap.next());
}
collection.remove(newBasicDBObject());
//JSON parse example
System.out.println("JSON parse example...");
String json="{'database' : 'mkyongDB','table' : 'hosting',"+
"'detail' : {'records' : 99, 'index' : 'vps_index1', 'active' : 'true'}}}";
DBObject dbObject=(DBObject)JSON.parse(json);
collection.insert(dbObject);
DBCursor cursorDocJSON=collection.find();
while(cursorDocJSON.hasNext()){
System.out.println(cursorDocJSON.next());
}
collection.remove(newBasicDBObject());
}catch(UnknownHostException e){
e.printStackTrace();
}catch(MongoException e){
e.printStackTrace();
}
}
}