MongoDB

安装并配置MongoDB

创建管理员账户并赋予权限

打开cmd,输入mongo,进入mongodb的命令页面

> use admin #进入admin数据库

switched to db admin

> db.createUser({user:"admin",pwd:"admin",roles:[{role:"root", db:"admin"}]})

user:”用户名“,

pwd:”密码”,

roles:[{role:”角色名“, db:”角色所属数据库”}, {role:”角色名2“, db:”角色所属数据库2”},…..]

各种角色的具体功能描述见:https://docs.mongodb.com/manual/core/security-built-in-roles/

用户添加成功会出现:成功的字样和添加的用户信息

修改配置文件

(位置:安装目录\bin 下)mongod.cfg文件

首先,将bind_ip改为0.0.0.0 (让其他电脑可以访问,用于远程连接,如果bind_ip是127.0.0.1的话,就只能本地访问)

然后找到 #security:改成下图所示,开启安全认证。

security: 
    authorization: enabled #注意缩进,参照其他的值来改,若是缩进不对可能导致后面服务不能重启

重启服务

重启MongoDB Server服务,启用认证!

验证的登陆

进入cmd,输入mongo,进入MongoDB shell.

直接输入命令会报错,因为没有认证登陆

img

接下来,进入账户所属数据库,再认证即可

> use admin

switched to db admin

> db.auth("用户名","密码")

1

> show dbs
admin    0.000GB
config   0.000GB
local    0.000GB
#这样登陆成功了

springboot整合MongoDB

pom.xml

<!--  Spring Boot MongoDB -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
    <version>2.0.2.RELEASE</version>
</dependency>

application.yml

data:
    mongodb:
      host: 127.0.0.1
      port: 27017
      username: root
      password: root
      authentication-database: admin
      database: test
      #uri方式会报错

model类

package com.example.mongodb.model;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

import java.util.Date;
import java.util.List;

@Document(collection = "article_info")
public class Article {

    @Id
    private String id;

    @Field("title")
    private String title;

    @Field("url")
    private String url;

    @Field("author")
    private String author;

    @Field("tags")
    private List<String> tags;

    @Field("visit_count")
    private Long visitCount;

    @Field("add_time")
    private Date addTime;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public List<String> getTags() {
        return tags;
    }

    public void setTags(List<String> tags) {
        this.tags = tags;
    }

    public Long getVisitCount() {
        return visitCount;
    }

    public void setVisitCount(Long visitCount) {
        this.visitCount = visitCount;
    }

    public Date getAddTime() {
        return addTime;
    }

    public void setAddTime(Date addTime) {
        this.addTime = addTime;
    }

    @Override
    public String toString() {
        return "article{" +
                "id='" + id + '\'' +
                ", title='" + title + '\'' +
                ", url='" + url + '\'' +
                ", author='" + author + '\'' +
                ", tags=" + tags +
                ", visitCount=" + visitCount +
                ", addTime=" + addTime +
                '}';
    }
}

继承MongoRepository接口

package com.example.mongodb.repository;

import com.example.mongodb.model.Article;
import org.springframework.data.mongodb.repository.MongoRepository;

/**
 * @author yanzt
 * @date 2018/6/27 14:30
 * @description
 */
public interface ArticleRepository extends MongoRepository<Article,String> {
}

测试

package com.example.mongodb.controller;

import com.example.annotation.IgnoreSecurity;
import com.example.mongodb.model.Article;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * MongoDB数据库的基本操作
 * */
@RestController
@RequestMapping("/testMongoDb")
public class testMongoDbController {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 初始化文章信息
     * */
    @RequestMapping("/init")
    @IgnoreSecurity
    public void initArticle(){
        Article article = new Article();

        article.setTitle("MongoTemplate的基本使用");
        article.setAuthor("yinjihuan");
        article.setUrl("http://cxytiandi.com/blog/detail/1");
        article.setTags(Arrays.asList("java", "mongodb", "spring"));
        article.setVisitCount(0L);
        article.setAddTime(new Date());

        mongoTemplate.save(article);


        //批量添加
        List<Article> articles = new ArrayList<>();
        for(int i = 0 ;i < 10 ;i++){
            article = new Article();

            article.setTitle("MongoTemplate的基本使用");
            article.setAuthor("yinjihuan");
            article.setUrl("http://cxytiandi.com/blog/detail/" + i);
            article.setTags(Arrays.asList("java", "mongodb", "spring"));
            article.setVisitCount(0L);
            article.setAddTime(new Date());

            articles.add(article);
        }
        mongoTemplate.insert(articles,Article.class);
    }

    @RequestMapping("/delete")
    @IgnoreSecurity
    public void delete(){
        //查询
        Query query = Query.query(Criteria.where("author").is("yinjihuan"));
        mongoTemplate.findAndRemove(query,Article.class);//删除第一条

//        mongoTemplate.remove(query,Article.class);//删除查询到的数据
//        mongoTemplate.findAllAndRemove(query,Article.class);//同上

//        mongoTemplate.getDb().drop();//删除所有

//        mongoTemplate.dropCollection(Article.class);//删除所有
//        mongoTemplate.dropCollection("article_info");//删除所有
    }

    @RequestMapping("/update")
    @IgnoreSecurity
    public void update(){
        //查询
        Query query = Query.query(Criteria.where("author").is("yinjihuan"));
        Update update = Update.update("title","MongoTemplate").set("visitCount",10);
        mongoTemplate.updateFirst(query,update,Article.class);//更新第一条
        mongoTemplate.updateMulti(query,update,Article.class);

        //query不存在则新增一条记录
        query = Query.query(Criteria.where("author").is("jason"));
        update = Update.update("title", "MongoTemplate").set("visitCount", 10);
        mongoTemplate.upsert(query,update,Article.class);

        //key不存在则新增
        /*update = Update.update("title", "MongoTemplate").set("money", 100);
        mongoTemplate.updateMulti(query, update, Article.class);*/

        //原有基础上做加法
        /*update = Update.update("title", "MongoTemplate").inc("money", 100);
        mongoTemplate.updateMulti(query, update, Article.class);*/

        //修改key
        /*update = Update.update("title", "MongoTemplate").rename("visitCount", "vc");
        mongoTemplate.updateMulti(query, update, Article.class);*/

        //update的pull方法用于删除tags数组中的java
        query = Query.query(Criteria.where("author").is("yinjihuan"));
        update = Update.update("title", "MongoTemplate").pull("tags", "java");
        mongoTemplate.updateMulti(query, update, Article.class);
    }

    /**查询操作*/
    @RequestMapping("/select")
    @IgnoreSecurity
    public void select(){
        Query query = Query.query(Criteria.where("author").is("yinjihuan"));
        List<Article> articles = mongoTemplate.find(query,Article.class);//查询符合条件的所有记录
        System.out.println("查询符合条件的所有记录:"+articles.toString());

        Article article = mongoTemplate.findOne(query,Article.class);//查询符合条件的第一条记录
        System.out.println("查询符合条件的第一条记录:"+article.toString());

        articles = mongoTemplate.findAll(Article.class);//查询集合中所有记录
        System.out.println("查询集合中所有记录:"+articles.toString());

        try {
            article = mongoTemplate.findById(new ObjectId("5afd4e0120180c05f8f0b93d"),Article.class);
            System.out.println("根据ID查询:"+article.toString());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        //in查询
        List<String> authors = Arrays.asList("yinjihuan", "jason");
        query = Query.query(Criteria.where("author").in(authors));
        articles = mongoTemplate.find(query, Article.class);
        System.out.println("in查询:"+articles.toString());

        //ne(!=)查询
        query = Query.query(Criteria.where("author").ne("jason"));
        articles = mongoTemplate.find(query, Article.class);
        System.out.println("ne(!=)查询:"+articles.toString());

        //lt(<)查询访问量小于10的文章
        query = Query.query(Criteria.where("visitCount").lt(10));
        articles = mongoTemplate.find(query, Article.class);
        System.out.println("lt(<)查询:"+articles.toString());

        //范围查询,大于5小于10
        query = Query.query(Criteria.where("visitCount").gt(5).lt(10));
        articles = mongoTemplate.find(query, Article.class);
        System.out.println("范围查询:"+articles.toString());

        //模糊查询,author中包含a的数据
        query = Query.query(Criteria.where("author").regex("a"));
        articles = mongoTemplate.find(query, Article.class);
        System.out.println("模糊查询:"+articles.toString());

        //数组查询,查询tags里数量为3的数据
        query = Query.query(Criteria.where("tags").size(3));
        articles = mongoTemplate.find(query, Article.class);
        System.out.println("数组查询:"+articles.toString());

        //or查询,查询author=jason的或者visitCount=0的数据
        query = Query.query(Criteria.where("").orOperator( Criteria.where("author").is("jason"), Criteria.where("visitCount").is(0)));
        articles = mongoTemplate.find(query, Article.class);
        System.out.println("or查询:"+articles.toString());

    }
}

   转载规则


《MongoDB》 yywzt 采用 知识共享署名 4.0 国际许可协议 进行许可。
 上一篇
SpringBoot配置WebSocket SpringBoot配置WebSocket
配置WebSocket实现简易聊天室添加相应依赖pom.xml <dependency> <groupId>org.springframework.boot</groupId> <a
2018-06-23
下一篇 
MySql中truncate()与format的区别 MySql中truncate()与format的区别
mysql中 truncate() 和 format() 保留小数位数的区别:truncate() 直接截取,不四舍五入。format() 会四舍五入,返回类型是字符串,因为满3位会加一个逗号,可以考虑用convert(); 例如:form
2018-06-23
  目录