本文目录一览:
- 1、如何用Java操作MongoDB
- 2、Java如何获取JSON的内容
- 3、java+mongodb的正确使用方法!
- 4、java中mongodb嵌套json查询?
- 5、Java如何读取json文件并将其存入Mongodb数据库中
如何用Java操作MongoDB
HelloWorld程序
学习任何程序的第一步,都是编写HelloWorld程序,我们也不例外,看下如何通过Java编写一个HelloWorld的程序。
首先,要通过Java操作Mongodb,必须先下载Mongodb的Java驱动程序,可以在这里下载。
新建立一个Java工程,将下载的驱动程序放在库文件路径下,程序代码如下:
package com.mkyong.core;
import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
/**
* Java + MongoDB Hello world Example
*
*/
public class App {
public static void main(String[] args) {
try {
//实例化Mongo对象,连接27017端口
Mongo mongo = new Mongo("localhost", 27017);
//连接名为yourdb的数据库,假如数据库不存在的话,mongodb会自动建立
DB db = mongo.getDB("yourdb");
// Get collection from MongoDB, database named "yourDB"
//从Mongodb中获得名为yourColleection的数据集合,如果该数据集合不存在,Mongodb会为其新建立
DBCollection collection = db.getCollection("yourCollection");
// 使用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("id", 1001);
// 使用collection的find方法查找document
DBCursor cursor = collection.find(searchQuery);
//循环输出结果
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
System.out.println("Done");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}
最后,输出的结果为:
{ "_id" : { "$oid" : "4dbe5596dceace565d229dc3"} ,
"id" : 1001 , "msg" : "hello world mongoDB in Java"}
Done
在上面的例子中,演示了使用Java对Mongodb操作的重要方法和步骤,首先通过创建Mongodb对象,传入构造函数的参数是Mongodb的数据库所在地址和端口,然后使用
getDB方法获得要连接的数据库名,使用getCollection获得数据集合的名,然后通过新建立BasicDBObject对象去建立document,最后通过collection的insert方法,将建立的document保存到数据库中去。而collection的find方法,则是用来在数据库中查找document。
从Mongodb中获得collection数据集
在Mongodb中,可以通过如下方法获得数据库中的collection:
DBCollection collection = db.getCollection("yourCollection");
如果你不知道collection的名称,可以使用db.getCollectionNames()获得集合,然后再遍历,如下:
DB db = mongo.getDB("yourdb");
Set collections = db.getCollectionNames();
for(String collectionName : collections){
System.out.println(collectionName);
}
完成的一个例子如下:
package com.mkyong.core;
import java.net.UnknownHostException;
import java.util.Set;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
/**
* Java : Get collection from MongoDB
*
*/
public class GetCollectionApp {
public static void main(String[] args) {
try {
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("yourdb");
SetString collections = db.getCollectionNames();
for (String collectionName : collections) {
System.out.println(collectionName);
}
DBCollection collection = db.getCollection("yourCollection");
System.out.println(collection.toString());
System.out.println("Done");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}
Mongodb中如何插入数据
下面,讲解下如何使用4种方式,将JSON数据插入到Mongodb中去。首先我们准备JSON
格式的数据,如下:
{
"database" : "mkyongDB",
"table" : "hosting",
"detail" :
{
records : 99,
index : "vps_index1",
active : "true"
}
}
}
我们希望用不同的方式,通过JAVA代码向Mongodb插入以上格式的JSON数据
第一种方法,是使用BasicDBObject,方法如下代码所示:
BasicDBObject document = new BasicDBObject();
document.put("database", "mkyongDB");
document.put("table", "hosting");
BasicDBObject documentDetail = new BasicDBObject();
documentDetail.put("records", "99");
documentDetail.put("index", "vps_index1");
documentDetail.put("active", "true");
document.put("detail", documentDetail);
collection.insert(document);
第二种方法是使用BasicDBObjectBuilder对象,如下代码所示:
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());
第三种方法是使用Map对象,代码如下:
Map documentMap =new HashMap();
documentMap.put("database", "mkyongDB");
documentMap.put("table", "hosting");
Map documentMapDetail =new HashMap();
documentMapDetail.put("records", "99");
documentMapDetail.put("index", "vps_index1");
documentMapDetail.put("active", "true");
documentMap.put("detail", documentMapDetail);
collection.insert(new BasicDBObject(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 =new Mongo("localhost", 27017);
DB db = mongo.getDB("yourdb");
// get a single collection
DBCollection collection = db.getCollection("dummyColl");
// BasicDBObject example
System.out.println("BasicDBObject example...");
BasicDBObject document =new BasicDBObject();
document.put("database", "mkyongDB");
document.put("table", "hosting");
BasicDBObject documentDetail =new BasicDBObject();
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(new BasicDBObject());
// 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(new BasicDBObject());
// Map example
System.out.println("Map example...");
Map documentMap =new HashMap();
documentMap.put("database", "mkyongDB");
documentMap.put("table", "hosting");
Map documentMapDetail =new HashMap();
documentMapDetail.put("records", "99");
documentMapDetail.put("index", "vps_index1");
documentMapDetail.put("active", "true");
documentMap.put("detail", documentMapDetail);
collection.insert(new BasicDBObject(documentMap));
DBCursor cursorDocMap = collection.find();
while(cursorDocMap.hasNext()){
System.out.println(cursorDocMap.next());
}
collection.remove(new BasicDBObject());
// 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(new BasicDBObject());
}catch(UnknownHostException e){
e.printStackTrace();
}catch(MongoException e){
e.printStackTrace();
}
}
}
Java如何获取JSON的内容
如果不是Android开发环境的话,首先需要引入处理JSON数据的包:json-lib-2.2.3-jdk15.jar
Java样例程序如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class DoJSON {
public static void main(String[] args) {
JSONArray employees = new JSONArray(); //JSON数组
JSONObject employee = new JSONObject(); //JSON对象
employee.put("firstName", "Bill"); //按“键-值”对形式存储数据到JSON对象中
employee.put("lastName", "Gates");
employees.add(employee); //将JSON对象加入到JSON数组中
employee.put("firstName", "George");
employee.put("lastName", "Bush");
employees.add(employee);
employee.put("firstName", "Thomas");
employee.put("lastName", "Carter");
employees.add(employee);
System.out.println(employees.toString());
for(int i=0; iemployees.size(); i++) {
JSONObject emp = employees.getJSONObject(i);
System.out.println(emp.toString());
System.out.println("FirstName :\t" + emp.get("firstName"));
System.out.println("LastName : \t" + emp.get("lastName"));
}
}
}
运行效果:
[{"firstName":"Bill","lastName":"Gates"},{"firstName":"George","lastName":"Bush"},{"firstName":"Thomas","lastName":"Carter"}]
{"firstName":"Bill","lastName":"Gates"}
FirstName : Bill
LastName : Gates
{"firstName":"George","lastName":"Bush"}
FirstName : George
LastName : Bush
{"firstName":"Thomas","lastName":"Carter"}
FirstName : Thomas
LastName : Carter
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){
System.out.println(str);
}
public static void main(String[] args) {
try {
//创建连接
Mongo m=new Mongo("127.0.0.1", 27017);
//得到数据库
DB db=m.getDB("sun");
//得到所有数据库
// ListString 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("stu");
//查看一个表的索引
// 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);
// //批量插入
// ListDBObject datas=new ArrayListDBObject();
// for(int i=0;i10;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());
//添加
// MapObject,Object map=new HashMapObject,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());
// ListDBObject list=coll.find().toArray();
// for(Object obj:list){
// System.out.println(obj);
// }
// DBObject dbc=new BasicDBObject();
// dbc.put("name", 1111);
// ListDBObject list=new ArrayListDBObject();
// 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 21y23:"+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嵌套json查询?
fastjson-1.1.2.jar 可以用这个jar包实现 java里面 json字符串和对象之间的互转
Java如何读取json文件并将其存入Mongodb数据库中
因为Java操作mongodb需要使用相关的ORM驱动,所以你最好是读取json数据后转成Java对象然后调用驱动方法存入到数据库中即可。