在mongodb数据中,内嵌文档就是在一个文档中包含了另外一个文档,其中优缺点
EmbedDocDao类:
package com.what21.mdb.dao.embed;
import java.util.Set;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.what21.mdb.dao.MongoContext;
public final class EmbedDocDao {
private MongoContext context;
public EmbedDocDao(MongoContext context){
this.context = context;
}
/**
* 保存内嵌文档
*
* @param docName
*/
public boolean save(String docName){
// 数据库集合
DBCollection dbColl = context.getDatabase().getCollection(docName);
// 操作集合
BasicDBObject attrs = new BasicDBObject();
attrs.put("name", "name");
// 内嵌文档
BasicDBObject[] addrAttrs = new BasicDBObject[4];
for(int i=0;i<4;i++){
BasicDBObject addrAttr = new BasicDBObject();
addrAttr.put("province", "山西");
addrAttr.put("city", "太原");
addrAttr.put("area", "杏花岭");
addrAttr.put("detail", "" + (i+1) + "号");
addrAttrs[i] = addrAttr;
}
attrs.put("address", addrAttrs);
dbColl.insert(attrs);
return true;
}
/**
* @param docName
* @return
*/
public boolean findOne(String docName){
// 数据库集合
DBCollection dbColl = context.getDatabase().getCollection(docName);
// 查询一条数据
DBObject objAttrs = dbColl.findOne();
// 所有返回内容
Set keySet = objAttrs.keySet();
for(String key : keySet){
Object value = objAttrs.get(key);
String type = value.getClass().getName();
System.out.println("key: " + key + ",值类型:" + type);
}
//
String name = (String)objAttrs.get("name");
System.out.println("key: name ,value:" + name);
// 内嵌文档
BasicDBList dbIntList = (BasicDBList)objAttrs.get("address");
System.out.println("key: address ,value:{" );
for(int i=0;i
BasicDBObject dbObj = (BasicDBObject)dbIntList.get(i);
System.out.print("province : " + dbObj.get("province") + "\t");
System.out.print("city : " + dbObj.get("city") + "\t");
System.out.print("area : " + dbObj.get("area") + "\t");
System.out.print("detail : " + dbObj.get("detail") + "\n");
}
System.out.println("}" );
return true;
}
}
MongoContext类使用上一节的,请点击这里。
EmbedDocDaoTest类:
package com.what21.mdb.dao.embed;
import com.what21.mdb.dao.MongoContext;
public class EmbedDocDaoTest {
/**
* @param args
*/
public static void main(String[] args) {
MongoContext context = new MongoContext();
context.setHost("127.0.0.1");
context.setPort(27017);
context.setDatabase("what21");
EmbedDocDao edDao = new EmbedDocDao(context);
// 保存数据
// edDao.save("demo2");
// 查看数据类型 db.demo2.findOne();
edDao.findOne("demo2");
context.close();
}
}