一、什么是MongoDB?
MongoDB 是一个基于分布式文件存储的数据库。它是一个介于关系型数据库和非关系型数据库之间的产品,是非关系型数据库当中功能最丰富
一、什么是MongoDB?
MongoDB 是一个基于分布式文件存储的数据库。它是一个介于关系型数据库和非关系型数据库之间的产品,是非关系型数据库当中功能最丰富也是最像关系型数据库的。
MongDB优点:1.有很强的的扩展性;
2.支持多种编程语言;
3.面向文档存储,操作比较简单;
缺点:1.不支持事务; 2.不能进行多表联查;
二、MongoDB基本操作
1.产看所有库
show dbs;
2.创建库
use 库名;
注:如果库中没有数据,就会是一个虚拟库,查看库的时候不会显示该库
3.查看当前库
db;
4.删除库(危险操作!一般不使用)
db.dropDatabase();
三.java操作MogoDB
在java中使用mongoDB之前,首先需要java连接mongoDB的第三方驱动包(通过在xml文件中添加依赖)
1.新增
public class AddDemo { public static void main(String[] args) { //获取链接 MongoClient mc = new MongoClient("localhost",27017); //获取库对象 MongoDatabase db = mc.getDatabase("student"); //获取集合对象 MongoCollection<Document> collection = db.getCollection("student"); //新增 Document document = new Document(); document.put("name", "周子舒"); document.put("sex", "男"); document.put("age", 18); document.put("birthday",new Date()); //添加一条数据 collection.insertOne(document); //添加多条数据 Document document1= new Document(); document1.put("name", "钟无艳"); document1.put("sex", "女"); document1.put("age", 18); document1.put("birthday",new Date()); Document document2= new Document(); document2.put("name", "貂蝉"); document2.put("sex", "女"); document2.put("age", 1); document2.put("birthday",new Date()); ArrayList<Document> list = new ArrayList<Document>(); list.add(document1); list.add(document2); collection.insertMany(list); mc.close(); } }
2.删除
删除某条单个数据时,使用 MongoCollection 对象的 deleteOne() 方法,该方法接收一个数据类型为 Bson 的的对象作为过滤器筛选出需要删除的文档。注意deleteOne() 方法只会删除表中满足删除条件的第一条数据。JDBC驱动程序提供了 Filters 类来为所有的MongoDB查询操作提供静态方法。每个方法返回的BSON类型。
public void deleteOneTest(){ public static void main(String[] args) { //获取链接 MongoClient mc = new MongoClient("localhost",27017); //获取库对象 MongoDatabase db = mc.getDatabase("student"); //获取集合对象 MongoCollection<Document> collection = db.getCollection("student"); //删除条件 Bson filter = Filters.eq("age",18); //删除与筛选器匹配的单个文档 collection.deleteOne(filter); mc.close(); } }
Filters.eq() //匹配到等于指定值的数据 Filters.gt() //匹配到大于指定值的数据 Filters.gte() //匹配到大于等于定值的数据 Filters.lt() //匹配到小于指定值的数据
删除多条数据, 使用 MongoCollection 对象的 deleteMany() 方法,该方法会将匹配到的所有数据全部删除。
public class DeleteDemo { public static void main(String[] args) { //获取链接 MongoClient mc = new MongoClient("localhost",27017);