基本操作:
//1. 查看链接的MongoDB中的所有的库
MongoClient mc=new MongoClient("localhost",27017);
MongoIterable<String> listDatabaseNames=mc.listDatabaseNames();
for(String name:listDatabaseNames) {
System.out.println(name);
}
//2. 使用库查看库中的集合
//获取库对象
MongoDatabase db= mc.getDatabase("小汉堡");
//获取库中的集合
MongoIterable<String> collist=db.listCollectionNames();
for(String li:collist) {
System.out.println(li);
}
//3.获取集合对象
MongoCollection<Document> coll = db.getCollection("teacher");
System.out.println(coll);
mc.close();
添加数据
MongoDatabase db = mongoClient.getDatabase("小汉堡");
MongoCollection<Document> coll = db.getCollection("teacher");
Document doc=new Document();
doc.append("tname", "lili");
doc.append("tsex", "女");
doc.append("tbir", new Date());
doc.append("tage", 40);
//添加一条数据
coll.insertOne(doc);
Document doc1 = new Document();
doc1.append("tname", "ken");
doc1.append("tsex", "男");
doc1.append("tbir", "2010-1-1");
doc1.append("tage", 14);
Document doc2 = new Document();
doc2.append("tname", "peter");
doc2.append("tsex", "男");
doc2.append("tbir", "2000-1-1");
doc2.append("tage", 24);
List<Document> doclist = new ArrayList<Document>();
doclist.add(doc1);
doclist.add(doc2);
//添加多条数据
coll.insertMany(doclist);
System.out.println("添加成功");
修改数据
Bson b1 = Filters.eq("stuname", "赵六");
Document doc = new Document();
doc.append("$set", new Document("age",61));
// 更新一条数据
UpdateResult updateOne = coll.updateOne(b1, doc);
long matchedCount = updateOne.getMatchedCount();
long modifiedCount = updateOne.getModifiedCount();
System.out.println(matchedCount);
System.out.println(modifiedCount);
//过滤多个条件
Bson b1 = Filters.or(
Filters.eq("stuname", "赵六"),
Filters.eq("stuname", "小张"));
Document doc = new Document();
//$inc 累加
doc.append("$inc", new Document("age",100));
//更新多条数据
UpdateResult updateMany = coll.updateMany(b1, doc);
//matchedCount 包含匹配文件的数量. modifiedCount 包含修改后的文件数
long matchedCount = updateMany.getMatchedCount();
long modifiedCount = updateMany.getModifiedCount();
System.out.println(matchedCount);
System.out.println(modifiedCount);
删除数据
Document b1=new Document();
b1.append("tname", "ken");
//过滤一个条件
Bson b1 = Filters.lt("tage", 30);
//删除编号最小的
DeleteResult deleteOne = coll.deleteOne(b1);
long deletedCount = deleteOne.getDeletedCount();
System.out.println(deletedCount);
//过滤多个条件
Bson b1 = Filters.and(Filters.gt("tage",30),Filters.lt("tage", 80));
//同时删除多条数据
DeleteResult deleteMany = coll.deleteMany(b1);
long deletedCount = deleteMany.getDeletedCount();
System.out.println(deletedCount);
查询数据
//全查
FindIterable<Document> find = coll.find();
//条件查询
Bson b1 = Filters.eq("tname","lili");
//模糊查询
Bson b1 = Filters.regex("tname", "^k");
FindIterable<Document> find = coll.find(b1);
//分页查询 查第一页的三条数据
FindIterable<Document> find = coll.find().skip((1-1)*3).limit(3);
//排序 1:升序 -1:降序
FindIterable<Document> find = coll.find().sort(new Document("tage",-1));
for(Document doc:find) {
System.out.println(doc);
}