⑴ 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语句
参考如下
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
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();
}
}
}
⑷ 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完全匹配