Java操作mongodb

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/chenshengzun721/article/details/84184873
java实现mongodb的操作必须下载mongodb的java驱动包,上mongodb官方网站就可以下载对应的驱动包http://www.mongodb.org/,找到driver这个菜单找到java分支就可以下载相应的java驱动包了,每一个驱动包下面都有对应的开发文档,
package com.mongo;

import java.net.UnknownHostException;


import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;


public class SimpleTest {

private Mongo mg = null;
private DB db = null;
private DBCollection collection;

public void init(){
try {
mg = new Mongo();
db = mg.getDB("temp");
collection = db.getCollection("users");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}

public void destory(){
if(mg != null){
mg.close();
mg = null;
db = null;
collection = null;
System.gc();
}
}

public void add(){
DBObject user = new BasicDBObject();
user.put("name", "Jack");
user.put("age", 20);
user.put("sex", "男");
DBObject info = new BasicDBObject();
info.put("address", "广州");
info.put("qq", "12345678");
user.put("info", info);
collection.save(user);
}

public void queryAll(){
System.out.println("查询users的所有数据:");
//db游标
DBCursor cur = collection.find();
while (cur.hasNext()) {
DBObject user = cur.next();

System.out.println("id : " + user.get("_id") + "\tname : " + user.get("_name") + "\tage : " + user.get("_age"));
if(user.get("info") != null){
DBObject info = (DBObject) user.get("info");
System.out.println("info < -- > " + info.get("address") + "\t" + info.get("qq"));
}
}
}

public void queryOne(){
System.out.println("查询users的One数据:");
//db游标
DBObject user = collection.findOne();
if (user != null) {
System.out.println("id : " + user.get("_id") + "\tname : " + user.get("_name") + "\tage : " + user.get("_age"));
if(user.get("info") != null){
DBObject info = (DBObject) user.get("info");
System.out.println("info < -- > " + info.get("address") + "\t" + info.get("qq"));
}
}
}



public static void main(String[] args){
SimpleTest test = new SimpleTest();
test.init();
test.queryOne();
test.queryAll();
test.destory();
}
}
展开阅读全文

没有更多推荐了,返回首页