MongoDB将不同类对象存入同一个Collection

在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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值