最近初学了下mongoDB,作为比较火的一个NoSQL数据库,确实比较强大,但是这几天学下来更多的感觉到的是学习、使用都很方便。
首先是初学者体验使用方便,直接下载(http://www.mongodb.org/downloads)解压,然后启一下服务便可使用:mongod --dbpath your_db_data_dir,启动以后默认端口27017, 默认http端口28017,可以通过http://localhost: 28017 查看基本信息。当然,如果你还没有下载的想法,可以直接在其官网上尝试Try The Online Shell,就可以使用其来做各种操作,当然online的功能较少。
其次,一改关系数据库的表模型,mongodb是一个以松散的集合形势呈现,这种 no shema让我感觉非常方便。从开发人员的角度看,mongodb中的每一个数据对象就是一个JSON,所有的操作(save,update,find etc.)都可以像操作JSON一样,当然mongodb数据是一种叫做BSON格式的,即Binary JSON:http://bsonspec.org/ 。例如:
将文档{ name:”abc”,age:12}插入到users集合:
db.users.insert ({name:”abc”,age:12})
修改文档,增加其emails属性:
db.users.update(
{name:"abc"},
{"$set": {emails:["[email protected]","[email protected]"]}}
)
查找所有users文档:
db.users.find();
查找age > 20的前5个:
db.users.find({
age: {“$gt”:20}
}).limit(5)
删除:db.users.delete({name:”abc”})
这些基本的操作不一一例举,包括像index的操作,统计函数等,总之,一切都是文档:查询表达式是文档、返回数据是文档、修改数据的新值是文档、index的操作也是文档形式等等。另外,诸如其支持的MAPREDUCE操作,只需在其规范内定义自己的map和reduce函数即可完成简单MR计算;使用GridFS规范来存储大文件。
最后的方便之处就是对很多开发语言的支持,PHP, Java, Python, Ruby, Perl。这里我就使用Morphia来做一个非常简单demo: 假设一千个店铺(store)分布在不同的地方(place),每个地方都有一个二维的坐标(x,y)用来表示其位置,我们可以很方便的查找到诸如 离***地方最近的***店铺。整个例子分三步:
1) 准备数据
2) 测试数据是否准备好
3) 查找店铺
使用jars: mongo-2.7.0.jar, morphia-0.98.jar
下面是两个model类:
@Entity(value="stores",noClassnameStored=true) public class Store { @Id private ObjectId id; private String name; private String desc; @Embedded public Place place; @Override public String toString() { return "Store [desc=" + desc + ", id=" + id + ", name=" + name + ", place=" + place + "]"; } public Store(){} public Store(String name, String desc, Place place) { this.name = name; this.desc = desc; this.place = place; } //省略getter,setters }
@Embedded public class Place { private String name = ""; @Indexed(IndexDirection.GEO2D) private double[] loc = null; public Place(String name, double[] loc) { this.name = name; this.loc = loc; } public Place() { } @Override public String toString() { return "Place [loc=" + Arrays.toString(loc) + ", name=" + name + "]"; } //省略getter,setters }
因为morphia提供了BasicDao,所以这里就准备一个简单的Dao:
package morphia.dao; import java.util.List; import morphia.model.Place; import morphia.model.Store; import com.google.code.morphia.Datastore; import com.google.code.morphia.dao.BasicDAO; import com.google.code.morphia.query.Query; public class StoreDao extends BasicDAO{ public StoreDao(Datastore ds) { super(ds); ds.ensureIndexes(); ds.ensureCaps(); } /** * 查找离 p 最近的5个店铺 * @param p * @return */ public List findNearPlace(Place p) { return ds.createQuery(Store.class).field("place.loc").near(p.getLoc()[0], p.getLoc()[1]).limit(5).asList(); } /** * 查找离 p 最近的5个肯德基店 * @param p * @return */ public List findKFCNearPlace(Place p) { return ds.createQuery(Store.class).filter("name", "肯德基").field("place.loc").near(p.getLoc()[0], p.getLoc()[1]).limit(5).asList(); } /** * 删除所有店铺 */ public void deleteAllStore(){ Query q = ds.createQuery(Store.class); ds.delete(q); } }
接下来就可以写测试类了:
package mongo.morphia.test; import java.util.List; import morphia.dao.PlaceDao; import morphia.dao.StoreDao; import morphia.model.Place; import morphia.model.Store; import com.google.code.morphia.Datastore; import com.google.code.morphia.Morphia; import com.mongodb.Mongo; public class StoreDaoTest { public static String[] STORE_TYPE = {"肯德基","麦当劳","必胜客","吉野家","蒸功夫"}; public static StoreDaoTest m = new StoreDaoTest(); static DaoHolder daoHolder = new DaoHolder(); //测试保存,准备一千家店铺的数据 public void testSave(){ long start = System.currentTimeMillis(); for( int i = 0; i < 1000; i++){ double x = Math.round(Math.random() * 10000)/100.0D; double y = Math.round(Math.random() * 10000)/100.0D; Place p = new Place("Place_"+x+"_"+y,new double[]{x,y}); Store s = new Store(STORE_TYPE[i%5],STORE_TYPE[i%5]+"@"+p.getName(),p); daoHolder.storeDao.save(s); } System.out.println(System.currentTimeMillis() - start); } //测试删除 public void testDeleteAll(){ System.out.println("Before delete the number of stores is: " + daoHolder.storeDao.count()); daoHolder.storeDao.deleteAllStore(); System.out.println("After delete the number of stores is: " + daoHolder.storeDao.count()); } //根据地理位置查找 public void testFindNearPlace(){ Place p = new Place("somewhere",new double[]{23.5,67.8}); System.out.println("Find 5 stores near "+ p.toString()); Listlist = daoHolder.storeDao.findNearPlace(p); for( Store s : list) System.out.println(s.toString()); System.out.println("Find 5 KFC stores near "+ p.toString()); list = daoHolder.storeDao.findKFCNearPlace(p); for( Store s : list) System.out.println(s.toString()); } //查找所有store public void testFindAll(){ long start = System.currentTimeMillis(); List list = daoHolder.storeDao.find().asList(); for( Store s : list) System.out.println(s.toString()); System.out.println(System.currentTimeMillis() - start); } static class DaoHolder{ PlaceDao placeDao; StoreDao storeDao; public DaoHolder(){ try { Mongo mongo = new Mongo("localhost",27017); Morphia morphia = new Morphia(); Datastore ds = morphia.createDatastore(mongo, "testDB"); placeDao = new PlaceDao(ds); storeDao = new StoreDao(ds); } catch (Exception e) { e.printStackTrace(); } } } }
首先, 通过调用StoreDaoTest.m.testSave()保存一千家店铺,用来做数据准备。
其次,通过调用StoreDaoTest.m.testFindAll()查看数据是否ok,当然也可以通过shell窗口查看。
现在可以通过 StoreDaoTest.m.testFindNearPlace()来查找地方p附近的相关店铺了,在这个方法中,我查了两次,一次是查找离p[loc=[23.5, 67.8], name=somewhere]最近的任意五个店铺,dao中这样写:
ds.createQuery(Store.class).field("place.loc").near(p.getLoc()[0], p.getLoc()[1]).limit(5).asList();
第二次是查找离p[loc=[23.5, 67.8], name=somewhere]最近的五个肯德基店铺,dao中这样写:
ds.createQuery(Store.class).filter("name", "肯德基")
.field("place.loc").near(p.getLoc()[0], p.getLoc()[1]).limit(5).asList();
输出结果:
Find 5 stores near Place [loc=[23.5, 67.8], name=somewhere]
Store [desc=麦当劳@Place_24.42_67.77, id=4ef9cc2cec9dcb16b1b552d2, name=麦当劳, place=Place [loc=[24.42, 67.77], name=Place_24.42_67.77]]
Store [desc=蒸功夫@Place_24.32_70.0, id=4ef9cc2dec9dcb16b1b553b6, name=蒸功夫, place=Place [loc=[24.32, 70.0], name=Place_24.32_70.0]]
Store [desc=必胜客@Place_24.08_64.89, id=4ef9cc2dec9dcb16b1b5544f, name=必胜客, place=Place [loc=[24.08, 64.89], name=Place_24.08_64.89]]
Store [desc=肯德基@Place_21.05_65.88, id=4ef9cc2dec9dcb16b1b5539e, name=肯德基, place=Place [loc=[21.05, 65.88], name=Place_21.05_65.88]]
Store [desc=吉野家@Place_25.78_65.66, id=4ef9cc2cec9dcb16b1b551f3, name=吉野家, place=Place [loc=[25.78, 65.66], name=Place_25.78_65.66]]
Find 5 KFC stores near Place [loc=[23.5, 67.8], name=somewhere]
Store [desc=肯德基@Place_21.05_65.88, id=4ef9cc2dec9dcb16b1b5539e, name=肯德基, place=Place [loc=[21.05, 65.88], name=Place_21.05_65.88]]
Store [desc=肯德基@Place_21.13_74.42, id=4ef9cc2dec9dcb16b1b5550b, name=肯德基, place=Place [loc=[21.13, 74.42], name=Place_21.13_74.42]]
Store [desc=肯德基@Place_20.26_77.73, id=4ef9cc2cec9dcb16b1b55204, name=肯德基, place=Place [loc=[20.26, 77.73], name=Place_20.26_77.73]]
Store [desc=肯德基@Place_32.55_73.14, id=4ef9cc2cec9dcb16b1b552ae, name=肯德基, place=Place [loc=[32.55, 73.14], name=Place_32.55_73.14]]
Store [desc=肯德基@Place_19.01_77.68, id=4ef9cc2cec9dcb16b1b55209, name=肯德基, place=Place [loc=[19.01, 77.68], name=Place_19.01_77.68]]
最后当然也可以通过StoreDaoTest.m.testDeleteAll() 删除所有测试数据。例子很简单,是我这个礼拜学习的一个小结吧,不罗嗦了。当然很多mongodb的操作命令就不记录了,有用到了再查吧,接下来会去学习一下spring data整合mongodb。