⑴ mongoDB在 java中的事務怎麼實現
MongoDB自身是不提供事務處理的。如果要實現事務操作,必須自己寫實現代碼。
在為你的項目選定資料庫的時候,要根據你的項目來量身選擇。如果需要強事務操作的和數據一致性很高的地方,最好選擇健壯的關系行資料庫。
如果對事務處理要求不高,而對數據存取要求很高的,則選擇非關系型資料庫。
⑵ java對所有mongodb表進行增刪改查表名怎麼設置
一、MongoDB資料庫參數配置
1、推薦使用mongodb.cfg.properties配置,則在構造MongoDBService對象的時候只需調用無參構造方法即可自動完成配置。
源代碼:(完整項目文件下載鏈接:點擊打開鏈接)
MongoDBServiceImpl.java
public class MongoDBServiceImpl implements MongoDBService {private String dbName;private String collName;private DB db;//有參構造方法,指定資料庫名與集合名public MongoDBServiceImpl(String dbName, String collName) {this.dbName = dbName;this.collName = collName;try {db = getDb();} catch (Throwable e) {e.printStackTrace();}}//無參構造方法,返回配置文件配置的資料庫對象引用,如果配置文件中沒有設置則返回默認資料庫對象引用public MongoDBServiceImpl() {getDb();}/** 獲取資料庫對象,3種情況(優先順序從高到低):*1、構造方法指定2、配置文件指定3、默認資料庫*(情況2、3在MongoDButil中設置)*/public DB getDb() {if (this.db == null) {if (this.dbName == null) {this.db = MongoDBUtil.getDB();} else {this.db = MongoDBUtil.getDBByName(this.dbName);}}return this.db;}/** 獲取集合對象,3種情況(優先順序從高到低):*1、構造方法指定2、配置文件指定3、默認資料庫*(情況2、3在MongoDButil中設置)*/public DBCollection getCollection() {if(this.collName != null){return db.getCollection(this.collName);}else {return MongoDBUtil.getDBCollection();}}public DBObject map2Obj(Map<string, object=""> map) {DBObject obj = new BasicDBObject();if (map.containsKey("class") && map.get("class") instanceof Class)map.remove("class");obj.putAll(map);return obj;}//插入數據public void insert(DBObject obj) {getCollection().insert(obj);}//插入多條數據public void insertBatch(List<dbobject> list) {if (list == null || list.isEmpty()) {return;}List<dbobject> listDB = new ArrayList<dbobject>();for (int i = 0; i < list.size(); i++) {listDB.add(list.get(i));}getCollection().insert(listDB);}//刪除數據public void delete(DBObject obj) {getCollection().remove(obj);}//刪除多條數據public void deleteBatch(List<dbobject> list) {if (list == null || list.isEmpty()) {return;}for (int i = 0; i < list.size(); i++) {getCollection().remove(list.get(i));}}//獲取集合中的數據數量public long getCollectionCount() {return getCollection().getCount();}//查找符合條件的數據數量public long getCount(DBObject obj) {if (obj != null)return getCollection().getCount(obj);return getCollectionCount();}//查找符合條件的數據public List<dbobject> find(DBObject obj) {DBCursor cur = getCollection().find(obj);return DBCursor2list(cur);}//查找符合條件的數據並排序@Overridepublic List<dbobject> find(DBObject query, DBObject sort) {DBCursor cur;if (query != null) {cur = getCollection().find(query);} else {cur = getCollection().find();}if (sort != null) {cur.sort(sort);}return DBCursor2list(cur);}//查找符合條件的數據並排序,規定數據個數@Overridepublic List<dbobject> find(DBObject query, DBObject sort, int start,int limit) {DBCursor cur;if (query != null) {cur = getCollection().find(query);} else {cur = getCollection().find();}if (sort != null) {cur.sort(sort);}if (start == 0) {cur.batchSize(limit);} else {cur.skip(start).limit(limit);}return DBCursor2list(cur);}//將DBCursor轉化為list<dbobject>private List<dbobject> DBCursor2list(DBCursor cur) {List<dbobject> list = new ArrayList<dbobject>();if (cur != null) {list = cur.toArray();}return list;}//更新數據public void update(DBObject setFields, DBObject whereFields) {getCollection().updateMulti(whereFields, setFields);}//查詢集合中所有數據public List<dbobject> findAll() {DBCursor cur = getCollection().find();List<dbobject> list = new ArrayList<dbobject>();if (cur != null) {list = cur.toArray();}return list;}//由ID獲取數據public DBObject getById(String id) {DBObject obj = new BasicDBObject();obj.put("_id", new ObjectId(id));DBObject result = getCollection().findOne(obj);return result;}public String getDbName() {return dbName;}public void setDbName(String dbName) {this.dbName = dbName;this.db = MongoDBUtil.getDBByName(this.dbName);}public String getCollName() {return collName;}public void setCollName(String collName) {this.collName = collName;}@Overridepublic void printListDBObj(List<dbobject> list) {// TODO Auto-generated method stubfor(DBObject dbObject: list){System.out.println(dbObject);}}}</dbobject></dbobject></dbobject></dbobject></dbobject></dbobject></dbobject></dbobject></dbobject></dbobject></dbobject></dbobject></dbobject></dbobject></dbobject></string,>MongoDBUtil.java
⑶ 如何在java中使用mongodb
首先你需要安裝mongodb的JDBC驅動,比如mongo-java-driver-3.2.2.jar。然後把這個jar包引用到你的程序中。
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC{
public static void main( String args[] ){
try{
// 連接到 mongodb 服務
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 連接到資料庫
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
⑷ java怎麼連接mangodb需要哪些步驟
開發環境:
System:Win7
IDE:eclipse
Database:mongoDB
開發依賴庫:
JavaEE5、mongo-2.5.3.jar、junit.jar、org.hamcrest.core_1.1.0.v20090501071000.jar
一、准備工作
1、下載Mongodb對java支持jar包
jar包下載地址:
mongoDB對Java的相關支持、技術:http://www.mongodb.org/display/DOCS/Java+Language+Center
驅動源碼下載:https://download.github.com/mongodb-mongo-java-driver-r2.6.1-7-g6037357.zip
在線查看源碼:https://github.com/mongodb/mongo-java-driver
2、下面建立一個JavaProject工程,導入下載下來的驅動包。即可在Java中使用mongoDB,目錄如下:
二、Java操作MongoDB示例
在本示例之前你需要啟動mongod.exe的服務,啟動後,下面的程序才能順利執行;
1、建立simpleTest.java,完成簡單的mongoDB資料庫操作
Mongomongo=newMongo();
這樣就創建了一個MongoDB的資料庫連接對象,它默認連接到當前機器的localhost地址,埠是27017。
DBdb=mongo.getDB(「test」);
這樣就獲得了一個test的資料庫,如果mongoDB中沒有創建這個資料庫也是可以正常運行的。mongoDB可以在沒有創建這個資料庫的情況下,完成數據的添加操作。當添加的時候,沒有這個庫,mongoDB會自動創建當前資料庫。
得到了db,下一步我們要獲取一個「聚集集合DBCollection」,通過db對象的getCollection方法來完成。
DBCollectionusers=db.getCollection("users");
這樣就獲得了一個DBCollection,它相當於我們資料庫的「表」。
查詢所有數據:
DBCursorcur=users.find();
while(cur.hasNext()){
System.out.println(cur.next());
}
完整源碼:
packagecom.mongodb;
importjava.net.UnknownHostException;
importcom.mongodb.util.JSON;
publicclasssimpleTest{
publicstaticvoidmain(String[]args)throwsUnknownHostException,MongoException{
Mongomg=newMongo();
//查詢所有的Database
for(Stringname:mg.getDatabaseNames()){
System.out.println("dbName:"+name);
}
DBdb=mg.getDB("test");
//查詢所有的聚集集合
for(Stringname:db.getCollectionNames()){
System.out.println("collectionName:"+name);
}
DBCollectionusers=db.getCollection("users");
//查詢所有的數據
DBCursorcur=users.find();
while(cur.hasNext()){
System.out.println("while="+cur.next());
}
System.out.println("count="+cur.count());
System.out.println("CursorId="+cur.getCursorId());
System.out.println("cur="+JSON.serialize(cur));
}
}
2、完成CRUD操作,首先建立一個curdTset.java,基本測試代碼如下:
packagecom.mongodb;
importjava.net.UnknownHostException;
importjava.util.ArrayList;
importjava.util.List;
importorg.bson.types.ObjectId;
importorg.junit.After;
importorg.junit.Before;
importorg.junit.Test;
importcom.mongodb.util.JSON;
publicclasscurdTset{
privateMongomg=null;
privateDBdb;
privateDBCollectionusers;//連接的mongodb資料庫
@Before
publicvoidinit(){
System.out.println("TestBefore...");
try{
mg=newMongo();
//mg=newMongo("localhost",27017);
}catch(UnknownHostExceptione){
e.printStackTrace();
}catch(MongoExceptione){
e.printStackTrace();
}catch(Exceptione){
e.printStackTrace();
}
//獲取testDB;如果默認沒有創建,mongodb會自動創建
db=mg.getDB("test");
//獲取usersDBCollection;如果默認沒有創建,mongodb會自動創建
users=db.getCollection("users");
}
@After
publicvoiddestory(){
System.out.println("TestAfter...");
if(mg!=null){
mg.close();
}
mg=null;
db=null;
users=null;
System.gc();
}
publicvoidprint(Objecto){
System.out.println(o);
}
privatevoidqueryAll(){
print("查詢users的所有數據:");
//db游標
DBCursorcur=users.find();
inti=1;
while(cur.hasNext()){
print("記錄"+i+":"+cur.next());
i++;
}
}
@Test
publicvoidadd(){
//先查詢所有數據
queryAll();
System.out.println("===============================ADDstart=======================================");
print("ADDcount:"+users.count());
DBObjectuser=newBasicDBObject();
user.put("name","hoojo");
user.put("age",24);
user.put("sex","男");
print(users.save(user).getN());
//添加多條數據,傳遞Array對象
print(users.insert(user,newBasicDBObject("name","tom")).getN());
//添加List集合
Listlist=newArrayList();
list.add(user);
DBObjectuser2=newBasicDBObject("name","lucy");
user.put("age",22);
list.add(user2);
//添加List集合
print(users.insert(list).getN());
//查詢下數據,看看是否添加成功
print("count="+users.count());
System.out.println("===============================ADDend=======================================");
//查詢所有數據
queryAll();
}
@Test
publicvoidremove(){
queryAll();
print("刪除id=4dde2b06feb038463ff09042:"+users.remove(newBasicDBObject("_id",newObjectId("4dde2b06feb038463ff09042"))).getN());
print("removeage>=24:"+users.remove(newBasicDBObject("age",newBasicDBObject("$gte",24))).getN());
System.out.println("===============================REMOVEend=======================================");
//查詢所有數據
queryAll();
}
@Test
publicvoidmodify(){
print("修改:"+users.update(newBasicDBObject("_id",newObjectId("4dde25d06be7c53ffbd70906")),newBasicDBObject("age",99)).getN());
print("修改:"+users.update(
newBasicDBObject("_id",newObjectId("4dde2b06feb038463ff09042")),
newBasicDBObject("age",121),
true,//如果資料庫不存在,是否添加
false//多條修改
).getN());
print("修改:"+users.update(
newBasicDBObject("name","haha"),
newBasicDBObject("name","dingding"),
true,//如果資料庫不存在,是否添加
false//false只修改第一條,true如果有多條就不修改
).getN());
//當資料庫不存在就不修改、不添加數據,當多條數據就不修改
//print("修改多條:"+coll.updateMulti(newBasicDBObject("_id",newObjectId("4dde23616be7c19df07db42c")),newBasicDBObject("name","199")));
System.out.println("===============================EDITend=======================================");
//查詢所有數據
queryAll();
}
@Test
publicvoidtestOthers(){
//查詢所有數據
queryAll();
DBObjectuser=newBasicDBObject();
user.put("name","hoojo");
user.put("age",24);
//JSON對象轉換
print("serialize:"+JSON.serialize(user));
//反序列化
print("parse:"+JSON.parse("{"name":"hoojo","age":24}"));
print("判斷tempCollection是否存在:"+db.collectionExists("users"));
//如果不存在就創建
if(!db.collectionExists("users")){
DBObjectoptions=newBasicDBObject();
options.put("size",20);
options.put("capped",20);
options.put("max",20);
print(db.createCollection("account",options));
}
//設置db為只讀
db.setReadOnly(true);
//只讀不能寫入數據
db.getCollection("test").save(user);
}
}
⑸ 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更新整個文檔
上篇博客介紹了java操作mongoDB進行對文件的處理。現在來介紹一下對文檔的處理。和對文件的處理一樣,也是通過java驅動中提供的幾個類相互作用完成的。這幾個類分別是:
DBCollection類:指定資料庫中指定集合的實例,提供了增刪改查等一系列操作。在關系型資料庫中,對數據的增刪改查操作是建立在表的基礎上的,在mongodb中是建立在集合的基礎上進行的。
DBObject介面:DBObject是鍵值的映射,因此,可以將DBObject的實現類作為查詢的返回結果,也可以作為查詢條件
DBCursor:游標,返回結果的集合。
下面是部分實例:
[java] view plain
Mongo mongo = new Mongo();
DB db = mongo.getDB("myMongoDB");
DBCollection course = db.getCollection("course");//對myMongoDB資料庫中course集合進行操作
//添加操作
//下面分別是創建文檔的幾種方式:1. .append() 2. .put() 3. 通過map 4. 將json轉換成DBObject對象
DBObject english = new BasicDBObject().append("name","english").append("score", 5).append("id",1);
course.insert(english);
DBObject math = new BasicDBObject();
math.put("id", 2);
math.put("name", "math");
math.put("score", 10);
course.insert(math);
Map<String,Object> map = new HashMap<String,Object>();
map.put("name","physics" );
map.put("score", 10);
map.put("id", 3);
DBObject physics= new BasicDBObject(map);
course.insert(physics);
String json ="{'name':'chemistry','score':10,'id':4}";
DBObject chemistry =(DBObject)JSON.parse(json);
course.insert(chemistry);
List<DBObject> courseList = new ArrayList<DBObject>();
DBObject chinese = new BasicDBObject().append("name","chinese").append("score", 10).append("id", 5);
DBObject history = new BasicDBObject().append("name", "history").append("score", 10).append("id", 6);
courseList.add(chinese);
courseList.add(history);
course.insert(courseList);
//添加內嵌文檔
String json2 =" {'name':'english','score':10,'teacher':[{'name':'柳松','id':'1'},{'name':'柳鬆鬆','id':2}]}";
DBObject english2= (DBObject)JSON.parse(json);
course.insert(english2);
List<DBObject> list = new ArrayList<DBObject>();
list.add(new BasicDBObject("name","柳松").append("id",1));
list.add(new BasicDBObject("name","柳鬆鬆").append("id",2));
DBObject english3= new BasicDBObject().append("name","english").append("score",10).append("teacher",list);
//查詢
//查詢所有、查詢一個文檔、條件查詢
DBCursor cur = course.find();
while(cur.hasNext()){
DBObject document = cur.next();
System.out.println(document.get("name"));
}
DBObject document = course.findOne();
String name=(String)document.get("name");
System.out.println(name);
//查詢學分=5的
DBObject query1 = new BasicDBObject("score",5);
DBObject query2 = new BasicDBObject("score",new BasicDBObject("$gte",5));
DBCursor cur2 = course.find(query2);
//條件表達式:$ge(>) $get(>=) $lt(<) $lte(<=) $ne(<>) $in $nin $all $exists $or $nor $where $type等等
//查找並修改
DBObject newDocument = course.findAndModify(new BasicDBObject("score",5), new BasicDBObject("score",15));
//更新操作
//q:更新條件 o:更新後的對象
course.update(new BasicDBObject("score",10), new BasicDBObject("test",15));
course.update(new BasicDBObject("score",15), new BasicDBObject("$set",new BasicDBObject("isRequired",true)));
//兩個的區別是,第一個更新是將{"test":15}這個文檔替換原來的文檔,
//第二個更新添加了條件表達式$set,是在原來文檔的基礎上添加"isRequired"這個鍵
//條件表達式:$set $unset $push $inc $push $push $addToSet $pull $pullAll $pop等等
//當_id相同時,執行save方法相當於更新操作
course.save(new BasicDBObject("name","math").append("_id", 1));
course.save(new BasicDBObject("name","數學").append("_id", 1));
//刪除符合條件的文檔
course.remove(new BasicDBObject("score",15));
//刪除集合及所有文檔
course.drop();<span style="font-family:Arial, Helvetica, sans-serif;"><span style="white-space: normal;">
</span></span>
上面只是介紹了一些簡單的操作,具體復雜的查詢更新可以根據需求再去查找文檔資料。其實,不管操作簡單還是復雜,其核心都是對DBObject和DBCollection的操作,主要掌握DBObject如何構造鍵值對,以及一些條件表達式。
⑺ 如何通過java操作 mongodb的 存儲過程
第一步:安裝MongoDB
無需太多的繁雜步驟,你只要在MongoDB官方網站查看安裝說明,根據自己的操作系統進行選擇適應的版本即可。
第二步:啟動MongoDB伺服器
這一步也很簡單。運行mongod.exe文件里的bin文件夾(我使用的是Windows OS系統),並啟動MongoDB伺服器。
在默認的情況下伺服器將啟動埠27017,你需要在安裝過程中創建將數據存儲在/data/db目錄里。
第三步:啟動MongoDB shell指令
你可以通過運行mongo.exe文件來啟動MongoBD shell.
第四步:利用MongoDB創建資料庫
利用MongoDB在MongoDB shell中輸入以下內容建立一個名為「company」的資料庫。
1.use company 記住,除非你在MangoDB里保存了一些東西,否則它不會自動為你保存。
使用下面的命令幫你查看可用的資料庫,它會顯示「company」尚未被創建。
1.show dbs;
第五步:在MongoDB中保存數據
使用下面的命令來保存employee 數據代表一個collection,將其命名為employees.
1.employee = {name : 「A」, no : 1}
2.db.employees.save(employee)
通過使用下面的命令來查看collection里的數據。
1.db.users.find();
如何使用Java操作MongoDB?
下面是是一段簡單的Java代碼,你可以在這里獲得mongo-java驅動。很簡單,只需要使用下面的代碼,重復上面的操作即可。
1.package com.eviac.blog.mongo;
2.
3.import java.net.UnknownHostException;
4.
5.import com.mongodb.BasicDBObject;
6.import com.mongodb.DB;
7.import com.mongodb.DBCollection;
8.import com.mongodb.DBCursor;
9.import com.mongodb.Mongo;
10.import com.mongodb.MongoException;
11.
12.public class MongoDBClient {
13.
14. public static void main(String[] args) {
15.
16. try {
17.
18. Mongo mongo = new Mongo(「localhost」, 27017);
19.
20. DB db = mongo.getDB(「company」);
21.
22. DBCollection collection = db.getCollection(「employees」);
23.
24. BasicDBObject employee = new BasicDBObject();
25. employee.put(「name」, 「Hannah」);
26. employee.put(「no」, 2);
27.
28. collection.insert(employee);
29.
30. BasicDBObject searchEmployee = new BasicDBObject();
31. searchEmployee.put(「no」, 2);
32.
33. DBCursor cursor = collection.find(searchEmployee);
34.
35. while (cursor.hasNext()) {
36. System.out.println(cursor.next());
37. }
38.
39. System.out.println(「The Search Query has Executed!」);
40.
41. } catch (UnknownHostException e) {
42. e.printStackTrace();
43. } catch (MongoException e) {
44. e.printStackTrace();
45. }
46.
47. }
48.
49.}
結果如下:
1.{ 「_id」 : { 「$oid」 : 「4fec74dc907cbe9445fd2d70」} , 「name」 : 「Hannah」 , 「no」 : 2}
2.The Search Query has Executed!
小結:
隨著互聯網Web2.0網站的興起,非關系型的資料庫現在成了一個極其熱門的新領域,非關系資料庫產品的發展也非常迅速。本文淺顯的談及了如何使用Java操作MongoDB以及了解MongoDB如何進行日常的資料庫操作的問題。
⑻ 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完全匹配
Pattern pattern = Pattern.compile("^王$", Pattern.CASE_INSENSITIVE);
3.2右匹配
Pattern pattern = Pattern.compile("^.*王$", Pattern.CASE_INSENSITIVE);
3.3左匹配
Pattern pattern = Pattern.compile("^王.*$", Pattern.CASE_INSENSITIVE);
3.4模糊匹配
Pattern pattern = Pattern.compile("^.*王.*$", Pattern.CASE_INSENSITIVE);
cond = new BasicDBObject();
cond.put("name",cond);
放入條件列表
condList.add(cond);
4、$gte/$lte/$gt/$lt
接1實例中,要篩選出年齡大於20且小於等於40的用戶,我們可以這樣:
cond = new BasicDBObject();
cond.append("age",new BasicDBObject("$gt",20));
cond.append("age",new BasicDBObject("$lte",40));
放入條件列表
condList.add(cond);
在日常的查詢中篩選的條件可能會有多個,而且多個條件之間都是且的關系,結合上例1、2、3、4中
將每種條件添加到條件列表中,我可以這樣:
BasicDBObject searchCond = new BasicDBObject();
searchCond.put("$and", condList);
然後查詢數據:
DBCursor ret = coll.find(searchCond);
⑼ java怎麼做到使用mongodb的原生命令來執行操作
public class MongoDBJDBC {
public static void main(String[] args) {
try {
// 實例化Mongo對象,連接27017埠
Mongo mongo = new Mongo("localhost", 27017);
// 連接名為yourdb的資料庫,假如資料庫不存在的話,mongodb會自動建立
DB db = mongo.getDB("test");
// Get collection from MongoDB, database named "yourDB"
// 從Mongodb中獲得名為yourColleection的數據集合,如果該數據集合不存在,Mongodb會為其新建立
DBCollection collection = db.getCollection("test1");
// 使用BasicDBObject對象創建一個mongodb的document,並給予賦值。
BasicDBObject document = new BasicDBObject();
//document.put("id", 1001);
//document.put("msg", "hello world mongoDB in Java");
// 將新建立的document保存到collection中去
//collection.insert(document);
// 創建要查詢的document
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "chen");
// 使用collection的find方法查找document
DBCursor cursor = collection.find(searchQuery);
// 循環輸出結果
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
System.out.println("Hello World");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}
⑽ java直接操作mongodb語句
參考如下
public class MongoDBJDBC {
public static void main(String[] args) {
try {
// 實例化Mongo對象,連接27017埠
Mongo mongo = new Mongo("localhost", 27017);
// 連接名為yourdb的資料庫,假如資料庫不存在的話,mongodb會自動建立
DB db = mongo.getDB("test");
// Get collection from MongoDB, database named "yourDB"
// 從Mongodb中獲得名為yourColleection的數據集合,如果該數據集合不存在,Mongodb會為其新建立
DBCollection collection = db.getCollection("test1");
// 使用BasicDBObject對象創建一個mongodb的document,並給予賦值。
BasicDBObject document = new BasicDBObject();
//document.put("id", 1001);
//document.put("msg", "hello world mongoDB in Java");
// 將新建立的document保存到collection中去
//collection.insert(document);
// 創建要查詢的document
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "chen");
// 使用collection的find方法查找document
DBCursor cursor = collection.find(searchQuery);
// 循環輸出結果
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
System.out.println("Hello World");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}