日期:2014-05-16 浏览次数:20364 次
1.下载安装和配置
?
windows:
?
安装Mongo数据库:
第一步:下载安装包:http://www.mongodb.org/downloads。 如果你懒得动,去附件里拿把。
第二步:新建目录“D:\MongoDB”,解压下载到的安装包,找到bin目录下面全部.exe文件,拷贝到刚创建的目录下。
第三步:在“D:\MongoDB”目录下新建“data”文件夹,它将会作为数据存放的根文件夹。
?
配置Mongo服务端:
打开CMD窗口,按照如下方式输入命令:
> d:
> cd D:\MongoDB
> mongod --dbpath D:\MongoDB\data
配置成功后会看到如下画面:
?
代表已经启动mongodb。
?
?
2.基本代码:
?
不多说,上java代码:
?
package com.mongodb; import java.net.UnknownHostException; public class MongoDb { /** * @param args */ public static void main(String[] args) { Mongo m; try { m = new Mongo("localhost", 27017); DB db = m.getDB("db_test"); DBCollection coll = db.getCollection("collection1"); findAll(coll); m.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } } private static void gt(DBCollection coll) { BasicDBObject query = new BasicDBObject(); query.put("i", new BasicDBObject("$gt", 5)); DBCursor cur = coll.find(query); while (cur.hasNext()) { System.out.println(cur.next()); } } private static void ne(DBCollection coll) { BasicDBObject query = new BasicDBObject(); query.put("i", new BasicDBObject("$ne", 3)); DBCursor cur = coll.find(query); while (cur.hasNext()) { System.out.println(cur.next()); } } private static void getOne(DBCollection coll) { BasicDBObject query = new BasicDBObject(); query.put("i", 4); DBCursor cur = coll.find(query); while (cur.hasNext()) { System.out.println(cur.next()); } } private static DBObject findFirstOne(DBCollection coll) { return coll.findOne(); } private static long getCount(DBCollection coll) { return coll.getCount(); } private static void findAll(DBCollection coll) { DBCursor cur = coll.find(); while (cur.hasNext()) { System.out.println(cur.next()); } } private static void insert(DBCollection coll) { BasicDBObject doc = new BasicDBObject(); doc.put("name", "MongoDB"); doc.put("type", "database"); doc.put("count", 1); BasicDBObject info = new BasicDBObject(); info.put("x", 203); info.put("y", 102); doc.put("info", info); coll.insert(doc); for (int i = 0; i < 10; i++) { coll.insert(new BasicDBObject().append("i", i)); } } }
?
?
?
第一集到此结束。