MongoDB:
1.MongoDB的提供了一个面向文档存储,操作起来比较简单和容易。
2.如果负载的增加,它可以分布在计算机网络中的其他节点上这就是所 谓的分片。
3. MongoDB支持各种编程语言:RUBY,PYTHON,JAVA,C++, PHP,C#等多种语言。
4.你可以通过本地或者网络创建数据镜像,这使得MongoDB有更强的 扩展性。
Java操作MongoDB
// 连接对象
MongoClient mc = new MongoClient("localhost", 27017);
//查看所有库
MongoIterable<String> listDatabaseNames = mc.listDatabaseNames();
MongoCursor<String> iterator = listDatabaseNames.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
// 库对象
MongoDatabase db = mc.getDatabase("库名");
//查看所有集合
MongoIterable<String> listCollectionNames = db.listCollectionNames();
for(String s : listCollectionNames) {
System.out.println(s);
}
// 集合对象
MongoCollection<Document> collection = db.getCollection("集合名");
// 添加一条数据
collection.insertOne(document对象);
// 一次添加多条数据
collection.insertMany(listdoc<document>集合);
//删除数据
DeleteResult deleteOne = collection.deleteOne(new Document("name","张三"));
//删除多条数据
DeleteResult deleteMany = collection.deleteMany(new Document("name","张三"));
Filters
该过滤器类为所有的MongoDB的查询操作静态工厂方法。每个方法返回BSON类型,又可以传递给期 望一个查询过滤器的任何方法的一个实例。
eq:匹配等于指定值的值。
gt:匹配大于指定值的值。
gte:匹配大于或等于指定值的值。
lt:匹配小于规定值的值。
lte:匹配是小于或等于规定值的值。
ne:匹配不等于指定值的所有值。
in:匹配任何在数组中指定的值。
nin:没有匹配数组中的规定值
//删除
Bson eq = Filters.eq("name", "哈哈哈");
// 多条件修改
Bson and = Filters.and(Filters.gte("age", 20),Filters.lte("age", 30));
UpdateResult updateOne = collection.updateOne(
and, new Document("$set",new Document("age", 20)),
new UpdateOptions().upsert(true));
new UpdateOptions().upsert(true)查不到数据新增
//修改数据
UpdateResult updateOne = collection.updateOne(
eq, new Document("$set",new Document("age", 20)));
//修改多条数据
UpdateResult updateMany = collection.updateMany(
and, new Document("$inc",new Document("age",100)));
//全查
MongoCollection<Document> = Db.getCollection("comment");
//多条件查询
Bson and = Filters.and(Filters.gte("age", 20),Filters.lte("age", 30));
FindIterable<Document> find = collection.find(and)
//模糊查询
Bson eq = Filters.regex("name", "张");
FindIterable<Document> find = collection.find(eq)
//排序查询
Document document = new Document("birthday",-1);
FindIterable<Document> find = collection.find(eq).sort(document);
//分页查询 .limit(2).skip(2)
FindIterable<Document> find = collection.find(eq).limit(2).skip(2);