mongoDB with java Driver

从mongoDB官方文档搬点东西吧,每次都去看英文网页太累,直接挑拣出一点基础方法来供自己检索。

mongoDB在java下的使用。


·建立连接:

MongoClient m = new MongoClient( "localhost" , 27017 );
DB db = m.getDB( "mydb" );

PS.貌似MongoClient在新版本中有更新,官方文档建议使用Mongo类(MongoClient的父类)


·认证(可选)

MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("test");
boolean auth = db.authenticate(myUserName, myPassword);

·获得集合列表

Set<String> colls = db.getCollectionNames();

·获得集合

DBCollection coll = db.getCollection("testCollection");

·新建文档


JSON例子:

{
   "name" : "MongoDB",
   "type" : "database",
   "count" : 1,
   "info" : {
               x : 203,
               y : 102
             }
}

java代码:

BasicDBObject doc = new BasicDBObject("name", "MongoDB").
                              append("type", "database").
                              append("count", 1)
                             .append("info", new BasicDBObject("x", 203).append("y", 102));

coll.insert(doc);

PS. append()与put()的区别和选择?以及与BasicDBObjectBuilder的append方法的区别和选择?


·查找findOne()

DBObject myDoc = coll.findOne();

·获得集合中的文档数

foo.getCount();


·Cursor的使用

DBCursor cursor = coll.find();
try {
   while(cursor.hasNext()) {
       System.out.println(cursor.next());
   }
} finally {
   cursor.close();
}

·查询文档

BasicDBObject query = new BasicDBObject("i", 71);

cursor = coll.find(query);

try {
   while(cursor.hasNext()) {
       System.out.println(cursor.next());
   }
} finally {
   cursor.close();
}

PS.与在shell中使用相比略麻烦吖~

带$操作符的例子:

db.things.find({j: {$ne: 3}, k: {$gt: 10} });

java中的使用:

BasicDBObject query = new BasicDBObject("j", new BasicDBObject("$ne", 3).
                                      append("k", new BasicDBObject("$gt", 10));

cursor = coll.find(query);

try {
   while(cursor.hasNext()) {
       System.out.println(cursor.next());
   }
} finally {
   cursor.close();
}

·创建索引

coll.createIndex(new BasicDBObject("i", 1));  // create index on "i", ascending

·获得索引列表

List<DBObject> list = coll.getIndexInfo();




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值