java操作mongodb的插入和修改

2013-08-06 11:13 来源:www.chinab4c.com 作者:ecshop专家

?? java操作mongodb的增加和修改过程,主要是通过使用本地的java来操作远程mongodb数据库,来完成对mongodb数据库的新增,以及修改的mongodb基本操作

package taobao;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;
class java2 {
?
???? public static void main(String[] args) {
???????? try{
???????? ??? Mongo mg = new Mongo("127.0.0.1",27017);
???????? ??? DB db = mg.getDB("admin");
??? ??? ??? boolean ok = db.authenticate("system","system".toCharArray());
???????? ??? //mg.auth("system","system");
??? ??????? //查询所有的Database
??? ??????? for (String name : mg.getDatabaseNames()) {
??? ??????????? //System.out.println("dbName: " + name);
??? ??????? }

??? ??????? db = mg.getDB("test");


??? ??????? DBCollection goods = db.getCollection("goods");
??? ??? ??? BasicDBObject?? ob = new BasicDBObject();

??? ??? ??? //ob.put("id",1);
??? ??? //??? goods.update(new BasicDBObject().append("name",1),ob,true);
??? ??????? //查询所有的数据
??? ??????? DBCursor cur = goods.find(new BasicDBObject("id",1));

??? ??????? while (cur.hasNext()) {

??? ??????????? DBObject? x = cur.next();
??? ??????????? System.out.println(x.get("name"));
??? ??????? }
??? ????? ??? /*for(int i=1;i<5;i++) {
??? ????? ??? ??? BasicDBObject x = new BasicDBObject();
??? ????? ??? ??? ?x.put("id",i);
??? ??? ??????? x.put("name","name"+i);
??? ??? ??????? goods.insert(x);
??? ????? ??? }*/
??? ????? ??? BasicDBObject a = new BasicDBObject();
??? ????? ??? BasicDBObject b = new BasicDBObject();
??? ????? ??? a.put("id",1);
??? ????? ??? b.put("name","ri");
??? ????? ??? goods.update(a,new BasicDBObject("$set",b));

???????? }catch(Exception e){
???????? ??? e.printStackTrace();
???????? }
???? }
}

?