導航:首頁 > 編程語言 > javamongodbupdate

javamongodbupdate

發布時間:2023-08-12 02:25:21

java用spring管理mongodb 怎麼修改mongodb中list中的數據

MongoClientclient=newMongoClient("192.168.0.110",27017);
DBCollectiondbCollection=client.getDB("test").getCollection("update_array");
dbCollection.drop();
dbCollection=client.getDB("test").getCollection("update_array");
BasicDBObjectdbObject=newBasicDBObject();
dbObject.append("id",583739819102582565L).append("kids",Arrays.asList("1","2","3"));
dbCollection.insert(dbObject);
System.out.println(dbCollection.findOne());
BasicDBObjectdbObject2=newBasicDBObject(dbObject);
dbObject2.append("kids",Arrays.asList("1","2","3","4"));
dbCollection.update(dbObject,dbObject2);
System.out.println(dbCollection.findOne());


測試結果:

{ "_id" : { "$oid" : "546f37f7d01de241a1e143e8"} , "id" : 583739819102582565 , "kids" : [ "1" , "2" , "3"]}

{ "_id" : { "$oid" : "546f37f7d01de241a1e143e8"} , "id" : 583739819102582565 , "kids" : [ "1" , "2" , "3" , "4"]}



<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.12.3</version>
</dependency>

⑵ 怎麼使用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如何構造鍵值對,以及一些條件表達式。

⑶ 高手幫幫忙,我剛接觸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){
.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表進行增刪改查表名怎麼設置

一、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();}}}
閱讀全文

與javamongodbupdate相關的資料

熱點內容
使用土地的有關證明文件包含哪些 瀏覽:493
數據標注哪裡可以接 瀏覽:482
在家自學編程下什麼學 瀏覽:705
最近很火的app軟體是什麼軟體 瀏覽:862
ai文字工具 瀏覽:157
蘭博玩游戲路徑怎麼選擇正確文件 瀏覽:972
淘寶直通車恢復老版本 瀏覽:510
播放草莓的圖片我都文件 瀏覽:55
微信大文件打不開 瀏覽:767
家裝合同准備哪些文件 瀏覽:296
應用bat合並excel文件 瀏覽:984
迅雷影音文件夾 瀏覽:109
makefile的文件路徑 瀏覽:392
計算機程序文件名擴展名為 瀏覽:982
網路游戲推廣策劃案 瀏覽:609
替換所有文件內容的代碼 瀏覽:960
不是常用數據模型有哪些 瀏覽:426
aspcms版本號 瀏覽:835
安卓怎麼用數據流量下載軟體 瀏覽:553
大眾手動空調數據流通道號是多少 瀏覽:303

友情鏈接