server.cmd
@echo off
cd bin
mongod -port 27017 -dbpath "d:\mongodb\dbdata" run
client.cmd
@echo off
cd bin
mongo 127.0.0.1:27017
mongodb与普通的关系型数据库类似有Database的概念,但没有表的概念,取而代之的是collection,没有row的概念,取而代之的是document,事物支持比较弱。
使用mongodb api操作数据库示例
……
DBAddress dbServer_2 = new DBAddress("localhost:27017");
DBAddress dbServer_1 = new DBAddress("localhost:27018");
Mongo Mongo = new Mongo(dbServer_1, dbServer_2);
if(Mongo.authenticate("dokhell", "unikey"))
throw DbAuthenticateException;
Set names = Mongo.getDB("bestpro").getCollectionNames();
DBCursor cursor = Mongo.getDB("bestpro").getCollection("bestpro").find();
for(DBObject obj : cursor) {
System.out.println(obj.get("a"));
}
DB db = Mongo.getDB("bestpro");
Collection coll = db.getCollection("bestpro");
……
当然,我们还需要一套orm来简化我们的数据库访问机制。这里有一个开源的orm框架morphia对mongdb提供良好的支持。
//操作聚合实体与值对象
Morphia morphia = new Morphia();
DBAddress dbAddr = new DBAddress("localhost:27017");
Mongo m = new Mongo(dbAddr);
BlogDao dao = new BlogDao(m, morphia, "bestpro");
dao.deleteByQuery(dao.createQuery().field("title").equal("this is next blog222"));
//System.out.println(dao.createQuery().limit(2).asList().get(1).getTitle());
ArticalEntity blog = new ArticalEntity();
//blog.setTitle("this is my fault222!`");
//dao.save(blog);
List comments = new ArrayList();
Comment comment1 = new Comment();
comment1.setName("comment1222");
comment1.setContent("this is the comment's content");
Comment comment2 = new Comment();
comment2.setName("comment1222");
comment2.setContent("this is the comment's content");
comments.add(comment2);
blog.setComments(comments);
ArticalEntity nextBlog = new ArticalEntity();
nextBlog.setTitle("this is next blog222");
blog.setNextBlog(nextBlog);
//InsertOrUpdate
dao.save(nextBlog);//关联的聚合实体需要在被包含的实体持久化之前持久化
dao.save(blog);
blog.setTitle("应该能够能支持中文的,因为全是二进制数据");
dao.save(blog);
//QueryAndUpdate(special update form)
//UpdateOperations ops = dao.createUpdateOperations().set("a", "2");
//dao.update(dao.createQuery(), ops);
//query
QueryResults entities = dao.find();
System.out.println(entities.asList().get(0).getTitle());
//pager
System.out.println(dao.createQuery().offset(0).limit(1).asList().get(0).getTitle());
跨collection操作
Morphia morphia = new Morphia();
DBAddress dbAddr = new DBAddress("127.0.0.1:27017");
Mongo m = new Mongo(dbAddr);
BlogDao blogDao = new BlogDao(m, morphia, "bestpro");
PersonDao personDao = new PersonDao(m, morphia, "bestpro");
PersonEntity person = new PersonEntity();
person.setName("my name is ……");
ArticalEntity artical = new ArticalEntity();
artical.setTitle("this is a title");
artical.setPerson(person);
personDao.save(person);
blogDao.save(artical);
相关资源链接:
mongodb quick start
http://www.mongodb.org/display/DOCS/Quickstart
mongodb驱动jar包+morphia的jar包下载:
http://files.iyunv.com/wJiang/mongo_dev.rar