当先锋百科网

首页 1 2 3 4 5 6 7

MongoDB 下载安装与启动

MongoDB下载地址 注意:win7最高适用MongoDB 4.2版本

  1. 下载压缩文件,在文件夹中新建data\db文件夹用来存储数据
    在这里插入图片描述
  2. 启动服务器 。在bin目录启动cmd 输入mongod --dbpath=…\data\db
  3. 启动客户端 。 在bin目录启动cmd 输入mongo

MongoDB基础操作

db.集合名称.insert/save/insertOne(文档) //添加
db.集合名称.update({条件},{操作种类:{文档}})
db.集合名称.remove(条件)

示例:

db.book.save({'name':'spring boot',type:'spring boot'}) //添加
db.book.remove({type:'spring boot'})	//删除
 //修改第一条
db.book.update({name:'spring boot'}, {$set:{name:'Spring Boot'}})
//修改所有
db.book.updateMany({name:'spring boot'}, {$set:{type:'spring'}})	
db.getCollection('book').find({})	//查询
db.book.find({type:'spring boot'})	//查询

Spring Boot 整合MongoDB(增删改查)

导入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

添加配置项

spring:
  data:
    mongodb:
      uri: mongodb://localhost/test

查询

@Test
void getTest() {
 //查询全部
  List<Book> all = mongoTemplate.findAll(Book.class);
  System.out.println(all);

 //根据id查询
  Book book = mongoTemplate.findById("1", Book.class);
  System.out.println(book);

 //根据条件查询
  Query query = new Query(Criteria.where("name").is("java"));
  List<Book> list2 = mongoTemplate.find(query, Book.class);
  System.out.println(list2);

 //查询并排序
  Query query2 = new Query().with(Sort.by(Sort.Direction.ASC,"name"));
  List<Book> list3 = mongoTemplate.find(query2,Book.class);
  System.out.println(list3);

 //分页查询
  Pageable pageable = (Pageable) PageRequest.of(0,4,Sort.by(Sort.Order.desc("id")));
  Query query1  =new Query().with(pageable);
  List<Book> list4 = mongoTemplate.find(query1, Book.class);
  System.out.println(list4);

 //查询数量
  long count = mongoTemplate.count(new Query(Criteria.where("author").is("asd")), Book.class);
  System.out.println("author 为asd的数量:"+count);
}

添加

@Autowired
MongoTemplate mongoTemplate;
 @Test
    void insert() {
        Book book1 = new Book("1", "CSS", "asd");
        Book book2 = new Book("2", "java", "asiudh");
        Book book3 = new Book("3", "C#", "aasdou");
        Book book4 = new Book("4", "javaSE", "jhgas");
        mongoTemplate.insert(book1);
        mongoTemplate.insert(book2);
        mongoTemplate.insert(book3);
        mongoTemplate.insert(book4);
    }

更新

@Test
void upd(){
   Query query = Query.query(Criteria.where("_id").is("4"));
   Update update = Update.update("name","javaEE");
   UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Book.class);
   System.out.println(updateResult);
}

删除

@Test
void del(){
    Book book = new Book();
    book.setId("111");
    mongoTemplate.remove(book);
}