⑴ 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