在mongodb中對應關係型資料庫中‘表’的概念為‘集合’,表中的資料結構是一致,mongodb以json格式儲存,集合資料是靈活的,mongodb的同一集合collection中可存不同結構的資料。下面為項目開發中測試的例子。
1.儲存
public void testSave(){
BizEntpris biz = new BizEntpris();
biz.setName("biztest01");
Country country = new Country();
country.setName("chinaName");
mongoTemplate.save(biz, "testMutiCollection");
mongoTemplate.save(country, "testMutiCollection");
BizEntpris biz2 = new BizEntpris();
biz2.setName("biztest02");
Country country2 = new Country();
country2.setName("chinaName02");
mongoTemplate.save(biz2, "testMutiCollection");
mongoTemplate.save(country2, "testMutiCollection");
}
2.查詢
public Map<String,Object> testQuery01(){
Map<String,Object> objMap = new HashMap<String, Object>();
Query query = new Query();
query.addCriteria(Criteria.where("name").is("biztest01"));
BizEntpris ent = mongoTemplate.findOne(query, BizEntpris.class, "testMutiCollection");
objMap.put("Entpris",ent);
Query q = new Query();
q.addCriteria(Criteria.where("name").is("chinaName01"));
Country country = mongoTemplate.findOne(q, Country.class, "testMutiCollection");
objMap.put("country", country);
List<Country> countryListAll = mongoTemplate.findAll(Country.class, "testMutiCollection");
objMap.put("countryListAll", countryListAll);//當findAll時查詢集合testMutiCollection所有的對象json資料,包含BizEntpris和Country的
List<BizEntpris> entListAll = mongoTemplate.findAll(BizEntpris.class, "testMutiCollection");
objMap.put("EntprisListAll", entListAll);//查詢集合testMutiCollection所有的對象json資料,包含BizEntpris和Country的
Query q1 = new Query();
System.out.println(Country.class.getSimpleName());
System.out.println(Country.class.getName());
q1.addCriteria(Criteria.where("_class").is(Country.class.getSimpleName()));
List<Country> countryList = mongoTemplate.find(q1,Country.class, "testMutiCollection");
objMap.put("countryListWithClass", countryList);
Query q2 = new Query();
q2.addCriteria(Criteria.where("_class").is(BizEntpris.class.getName()));
List<BizEntpris> entList = mongoTemplate.find(q2,BizEntpris.class, "testMutiCollection");
objMap.put("EntprisListWithClass", entList);
return objMap;
}