導航:首頁 > 編程語言 > javamongodb教程

javamongodb教程

發布時間:2022-08-05 08:06:17

❶ 關於mongoDB的$or 怎麼用java實現

舉例:
public static void selectAll() throws Exception{
//第一:實例化mongo對象,連接mongodb伺服器 包含所有的資料庫

//默認構造方法,默認是連接本機,埠號,默認是27017
//相當於Mongo mongo =new Mongo("localhost",27017)
Mongo mongo =new Mongo();

//第二:連接具體的資料庫
//其中參數是具體資料庫的名稱,若伺服器中不存在,會自動創建
DB db=mongo.getDB("myMongo");

//第三:操作具體的表
//在mongodb中沒有表的概念,而是指集合
//其中參數是資料庫中表,若不存在,會自動創建
DBCollection collection=db.getCollection("user");
BasicDBList condList = new BasicDBList();
BasicDBObject cond = null;

String ageStr = "function (){return parseFloat(this.id) > 2 && parseFloat(this.id) <= 4};";
cond = new BasicDBObject();
cond.put("$where",ageStr);

Pattern pattern = Pattern.compile("^.*明.*$", Pattern.CASE_INSENSITIVE);
BasicDBObject query =new BasicDBObject();
query.put("name", pattern);

condList.add(query);
condList.add(cond);
BasicDBObject searchCond = new BasicDBObject();
searchCond.put("$or", condList);

//查詢操作

DBCursor cursor=collection.find(searchCond);

System.out.println("mongodb中的user表結果如下:");
while(cursor.hasNext()){
System.out.println(cursor.next());
}
}

❷ mongodb教程在哪可以找到

個人比較推薦學雲網的《Mongodb開發視頻教程》,主要介紹當前比較主流的NoSQL技術,採用NoSQL中最為流行的Mongodb資料庫,主要介紹Mongdb資料庫的基本使用方法,介紹Mongodb的文檔對象操作方法,介紹Mongodb的管理操作,介紹Mongodb的高級部分,包括主從復制、副本集和分片,以及如何使用Java操作Mongodb資料庫來開發程序。希望能滿足你的需要。。。
滿意請採納

❸ 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

❹ 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語句

參考如下
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更新整個文檔

上篇博客介紹了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資料庫參數配置

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

public class MongoDBUtil {// 定義默認配置,1、IP地址 2、埠號 3、用戶名 4、密碼 5、配置文件位置名 6、資料庫名private static final String MONGODB_ADDRESS = "127.0.0.1";private static final int MONGODB_PORT = 27017;private static final String MONGODB_USERNAME = "root";private static final String MONGODB_PASSWORD = "";private static final String MONGODB_RESOURCE_FILE = "mongodb.cfg.properties";private static final String MONGODB_DBNAME = "test";private static final String MONGODB_COLLECTIONNAME = "test";// 定義靜態變數,1、Mongo對象(代表資料庫連接)2、DB對象(代表資料庫)3、集合名4、資料庫相關配置映射集合5、已獲取的資料庫連接private static Mongo mongo;private static DB db;private static DBCollection collection;private static Map<string, string=""> cfgMap = new HashMap<string, string="">();private static Hashtable<string, db=""> mongoDBs = new Hashtable<string, db="">();/*** 初始化Mongo的資料庫*/static {init();}/*** 獲取配置文件中配置的DB對象*/public static DB getDB() {return db;}/*** 獲取配置文件中配置的DBCollection對象*/public static DBCollection getDBCollection() {return collection;}/*** 根據資料庫名稱,得到資料庫 如果不存在,則創建一個該名稱的資料庫,並設置用戶名和密碼為配置文件中的參數值** @param dbName* @return DB*/@SuppressWarnings("deprecation")public static DB getDBByName(String dbName) {DB db = mongo.getDB(dbName);if (!mongoDBs.contains(db)) {System.out.println("add");db.addUser(cfgMap.get("mongo.db.username"),cfgMap.get("mongo.db.password").toCharArray());mongoDBs.put(dbName, db);}return db;}// ————————————————————————————————————初始化過程————————————————————————————————————/*** 獲取配置文件mongedb.cfg.properties的文件對象*/public static File getConfigFile() {String path = MongoDBUtil.class.getResource("/").getPath();String fileName = path + MONGODB_RESOURCE_FILE;System.out.println(fileName);File file = new File(fileName);if (file.exists()) {return file;}return null;}/*** 通過mongedb.cfg.properties配置文件初始化配置映射集合,如果沒有編寫配置文件,則載入程序指定的默認配置*/@SuppressWarnings("unchecked")private static void initCfgMap() {File file = getConfigFile();if (file != null) {Properties p = new Properties();try {p.load(new FileInputStream(file));for (Enumeration enu = p.propertyNames(); enu.hasMoreElements();) {String key = (String) enu.nextElement();String value = (String) p.getProperty(key);cfgMap.put(key, value);}} catch (IOException e) {System.out.println("載入Mongo配置文件失敗!");e.printStackTrace();}} else { // 如果沒有編寫配置文件,則載入默認配置cfgMap.put("mongo.db.address", MONGODB_ADDRESS);cfgMap.put("mongo.db.port", String.valueOf(MONGODB_PORT));cfgMap.put("mongo.db.username", MONGODB_USERNAME);cfgMap.put("mongo.db.password", MONGODB_PASSWORD);cfgMap.put("mongo.db.dbname", MONGODB_DBNAME);cfgMap.put("mongo.db.collectionname", MONGODB_COLLECTIONNAME);}}/*** 初始化Mongo的資料庫(將db指向相應對象引用,將collection指向相應對象引用,通過mongoDBs記錄現有資料庫對象)*/@SuppressWarnings("deprecation")private static void init() {initCfgMap();try {String address = cfgMap.get("mongo.db.address");int port = Integer.parseInt(cfgMap.get("mongo.db.port").toString());String dbName = cfgMap.get("mongo.db.dbname");String username = cfgMap.get("mongo.db.username");String password = cfgMap.get("mongo.db.password");String collectionName = cfgMap.get("mongo.db.collectionname");mongo = new Mongo(address, port);if (dbName != null && !"".equals(dbName)) {db = mongo.getDB(dbName);if (username != null && !"".equals(username)) {db.addUser(username, password.toCharArray());if (collectionName != null && !"".equals(collectionName)) {collection = db.getCollection(collectionName);}}mongoDBs.put(dbName, db);}} catch (Exception e) {e.printStackTrace();}}}

❽ java操作MongoDB使用強制索引的方法

DBCollection dbc = db.getCollection("role");

dbc.setHintFields(null);
雖然3.0以後版本中 DBCollection方法 已過時,可以將就用

直接用 $hint 操作符
db.users.find( { name: {}, $hint: { age : 1 } } )

參考地址
https://docs.mongodb.org/manual/reference/operator/meta/hint/#metaOp._S_hint

❾ java怎麼導出mongodb數據

java 操作mongodb插入、讀娶修改以及刪除基礎 本文主要講述如何使用Java操作MongoDB以及了解MongoDB如何進行日常的資料庫操作。文章內容如下:第一步:安裝MongoDB無需太多的繁雜步驟,你只要在MongoDB官方網站查看安裝說明。

閱讀全文

與javamongodb教程相關的資料

熱點內容
自己建了伺服器地址 瀏覽:698
命令按鈕的屬性設置 瀏覽:963
證券技術分析pdf 瀏覽:779
linux命令連接oracle 瀏覽:202
墊江停車收費樁怎麼上App 瀏覽:135
好興動app還款怎麼登錄不上去了 瀏覽:665
鄭州雲伺服器託管 瀏覽:722
伺服器地址跟蹤 瀏覽:980
免費google雲伺服器 瀏覽:516
摘譯和編譯的英文 瀏覽:359
熱泵壓縮機選型 瀏覽:121
op手機微信加密如何解除 瀏覽:386
如何在王牌戰爭找到高爆率伺服器 瀏覽:13
江浙小學語文輔導課用什麼APP 瀏覽:99
新夢幻大陸伺服器地址 瀏覽:241
網吧伺服器怎麼更換壁紙 瀏覽:530
linux命令方法 瀏覽:332
linux下載freetype 瀏覽:123
程序員入駐平台 瀏覽:327
程序員大戰外掛 瀏覽:745