MongoDB的集成与使用

MongoDB的集成与使用

资料来源
https://blog.csdn.net/qq_44766883/article/details/106444784
https://blog.csdn.net/qq_41107231/article/details/108028319
https://www.jianshu.com/p/711cb4dc4057
https://www.runoob.com/mongodb/mongodb-linux-install.html
自用,做思路记录。

1.Linux环境下的安装

1.下载

首先,从官网根据自己linux版本下载对应的mongoDB版本

https://www.mongodb.com/download-center#community

img

img

注意压缩包不要选择(shell) tgz,直接选择没有前缀的tgz即可
后来得知可以直接下载rpm文件,方便开机自启动,降低维护成本,有空再来研究

然后通过文件传输工具传输到linux中

2.安装

1.解压
tar -zxvf 文件名
2.添加path

将mongodb的bin目录添加到path中

export PATH=<mongodb-install-directory>/bin:$PATH

mongodb-install-directory是文件安装路径,不需要<>

3.创建存储目录和日志文件

默认情况下mongoDB启动后会初始化一下两个目录

  • 数据存储目录:/var/lib/mongodb
  • 日志文件目录:/var/log/mongodb

为了方便管理,我们可以自定义创建目录。

mkdir 存储路径/data
mkdir 存储路径/logs/mongod.log
4.创建配置文件

新增目录

mkdir 存储路径/etc

直接vi新增并修改配置文件

cd etc
vi mongodb.conf

将下面代码拷贝到mongodb.conf中

dbpath = /data/db #数据文件存放目录  
logpath = /data/logs/mongodb.log   #日志文件存放目录  
port = 27017  #端口  
fork = true  #以守护程序的方式启用,即在后台运行  
auth=true #验证用户名密码(先不开启)
logappend=true
bind_ip=0.0.0.0 #这里默认是127.0.0.1, 设置成0.0.0.0是表示所有IP地址都可以访问

3.启动

回到bin目录下

./mongod -config 路径/mongodb.conf

启动成功会看到类似提示

img

1.添加管理员用户

先通过mongod(自带的shell工具)连接服务器。

./mongo

mongodb的管理员用户数据是存放在admin库里面的,所以先打开admin库,执行以下命令创建管理员账户

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

创建成功会看到类似提示

img

添加完后,关掉mongodb服务

db.shutdownServer()

去配置文件中开启密码认证

auth=true #验证用户名密码

重新启动mongodb服务

./mongod -config mongodb.conf

登录

./mongo

这个时候必须要进行密码认证,不然做不了任何操作

use admin
db.auth("admin","123456")

返回1,就代表密码认证完成了。

这个时候输入

show dbs

就可以正常查看我们的数据库以及做各种操作了。

到这里,mongodb在linux上的部署就完成了。

2.客户端远程连接

1.官方连接工具

https://nosqlbooster.com/downloads

在这里插入图片描述

下载后打开

在这里插入图片描述

输入用户名密码,以及数据库

在这里插入图片描述

连接成功

在这里插入图片描述

2.开启防火墙

如果连接不成功,本地又能够成功启用,那多半就是防火墙造成的

解决方法

开启防火墙

systemctl start firewalld

防火墙状态

systemctl status firewalld

设置防火墙mongo放行端口

firewall-cmd --zone=public --add-port=27017/tcp

重启防火墙

firewall-cmd --reload

查看防火墙放行端口

firewall-cmd --list-ports

关闭防火墙端口

firewall-cmd --zone=public --remove-port=27017/tcp

设置开机启动防火墙

systemctl enable firewalld.service

设置开机禁用防火墙

systemctl disable firewalld.service

3.springboot下集成mongoDB

1.添加依赖

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

2.添加配置文件

spring:
  data:
    mongodb:
      host: 127.0.0.1
      port: 27017
      username: manager
      password: manager
      authentication-database: admin  #认证的库
      database: exam    #操作的库

3.工具类(搬运,还需要看看再用)

package top.codekiller.test.mongodb.util;
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.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author codekiller
 * @date 2020/5/30 15:53
 * Mongodb工具类
 */
@Component
public class MongodbUtils {

    public static MongodbUtils mongodbUtils;

    @PostConstruct
    public void init() {
        mongodbUtils = this;
        mongodbUtils.mongoTemplate = this.mongoTemplate;
    }

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
         * 保存数据对象,集合为数据对象中@Document 注解所配置的collection
         *
         * @param obj
         *            数据对象
         */
    public static void save(Object obj) {
        mongodbUtils.mongoTemplate.save(obj);
    }

    /**
         * 指定集合保存数据对象
         *
         * @param obj
         *            数据对象
         * @param collectionName
         *            集合名
         */
    public static void save(Object obj, String collectionName) {

        mongodbUtils.mongoTemplate.save(obj, collectionName);
    }

    /**
         * 根据数据对象中的id删除数据,集合为数据对象中@Document 注解所配置的collection
         *
         * @param obj
         *            数据对象
         */
    public static void remove(Object obj) {

        mongodbUtils.mongoTemplate.remove(obj);
    }

    /**
         * 指定集合 根据数据对象中的id删除数据
         *
         * @param obj
         *            数据对象
         * @param collectionName
         *            集合名
         */
    public static void remove(Object obj, String collectionName) {

        mongodbUtils.mongoTemplate.remove(obj, collectionName);
    }

    /**
         * 根据key,value到指定集合删除数据
         *
         * @param key
         *            键
         * @param value
         *            值
         * @param collectionName
         *            集合名
         */
    public static void removeById(String key, Object value, String collectionName) {

        Criteria criteria = Criteria.where(key).is(value);
        criteria.and(key).is(value);
        Query query = Query.query(criteria);
        mongodbUtils.mongoTemplate.remove(query, collectionName);
    }

    /**
         * 指定集合 修改数据,且仅修改找到的第一条数据
         *
         * @param accordingKey
         *            修改条件 key
         * @param accordingValue
         *            修改条件 value
         * @param updateKeys
         *            修改内容 key数组
         * @param updateValues
         *            修改内容 value数组
         * @param collectionName
         *            集合名
         */
    public static void updateFirst(String accordingKey, Object accordingValue, String[] updateKeys, Object[] updateValues,
                                   String collectionName) {

        Criteria criteria = Criteria.where(accordingKey).is(accordingValue);
        Query query = Query.query(criteria);
        Update update = new Update();
        for (int i = 0; i < updateKeys.length; i++) {
            update.set(updateKeys[i], updateValues[i]);
        }
        mongodbUtils.mongoTemplate.updateFirst(query, update, collectionName);
    }

    /**
         * 指定集合 修改数据,且修改所找到的所有数据
         *
         * @param accordingKey
         *            修改条件 key
         * @param accordingValue
         *            修改条件 value
         * @param updateKeys
         *            修改内容 key数组
         * @param updateValues
         *            修改内容 value数组
         * @param collectionName
         *            集合名
         */
    public static void updateMulti(String accordingKey, Object accordingValue, String[] updateKeys, Object[] updateValues,
                                   String collectionName) {

        Criteria criteria = Criteria.where(accordingKey).is(accordingValue);
        Query query = Query.query(criteria);
        Update update = new Update();
        for (int i = 0; i < updateKeys.length; i++) {
            update.set(updateKeys[i], updateValues[i]);
        }
        mongodbUtils.mongoTemplate.updateMulti(query, update, collectionName);
    }

    /**
         * 根据条件查询出所有结果集 集合为数据对象中@Document 注解所配置的collection
         *
         * @param obj
         *            数据对象
         * @param findKeys
         *            查询条件 key
         * @param findValues
         *            查询条件 value
         * @return
         */
    public static List<? extends Object> find(Object obj, String[] findKeys, Object[] findValues) {

        Criteria criteria = null;
        for (int i = 0; i < findKeys.length; i++) {
            if (i == 0) {
                criteria = Criteria.where(findKeys[i]).is(findValues[i]);
            } else {
                criteria.and(findKeys[i]).is(findValues[i]);
            }
        }
        Query query = Query.query(criteria);
        List<? extends Object> resultList = mongodbUtils.mongoTemplate.find(query, obj.getClass());
        return resultList;
    }

    /**
         * 指定集合 根据条件查询出所有结果集
         *
         * @param obj
         *            数据对象
         * @param findKeys
         *            查询条件 key
         * @param findValues
         *            查询条件 value
         * @param collectionName
         *            集合名
         * @return
         */
    public static List<? extends Object> find(Object obj, String[] findKeys, Object[] findValues, String collectionName) {

        Criteria criteria = null;
        for (int i = 0; i < findKeys.length; i++) {
            if (i == 0) {
                criteria = Criteria.where(findKeys[i]).is(findValues[i]);
            } else {
                criteria.and(findKeys[i]).is(findValues[i]);
            }
        }
        Query query = Query.query(criteria);
        List<? extends Object> resultList = mongodbUtils.mongoTemplate.find(query, obj.getClass(), collectionName);
        return resultList;
    }

    /**
         * 指定集合 根据条件查询出所有结果集 并排倒序
         *
         * @param obj
         *            数据对象
         * @param findKeys
         *            查询条件 key
         * @param findValues
         *            查询条件 value
         * @param collectionName
         *            集合名
         * @param sort
         *            排序字段
         * @return
         */
    public static List<? extends Object> find(Object obj, String[] findKeys, Object[] findValues, String collectionName ,String sort) {

        Criteria criteria = null;
        for (int i = 0; i < findKeys.length; i++) {
            if (i == 0) {
                criteria = Criteria.where(findKeys[i]).is(findValues[i]);
            } else {
                criteria.and(findKeys[i]).is(findValues[i]);
            }
        }
        Query query = Query.query(criteria);
        query.with(new Sort(Direction.DESC, sort));
        List<? extends Object> resultList = mongodbUtils.mongoTemplate.find(query, obj.getClass(), collectionName);
        return resultList;
    }

    /**
         * 根据条件查询出符合的第一条数据 集合为数据对象中 @Document 注解所配置的collection
         *
         * @param obj
         *            数据对象
         * @param findKeys
         *            查询条件 key
         * @param findValues
         *            查询条件 value
         * @return
         */
    public static Object findOne(Object obj, String[] findKeys, Object[] findValues) {

        Criteria criteria = null;
        for (int i = 0; i < findKeys.length; i++) {
            if (i == 0) {
                criteria = Criteria.where(findKeys[i]).is(findValues[i]);
            } else {
                criteria.and(findKeys[i]).is(findValues[i]);
            }
        }
        Query query = Query.query(criteria);
        Object resultObj = mongodbUtils.mongoTemplate.findOne(query, obj.getClass());
        return resultObj;
    }

    /**
         * 指定集合 根据条件查询出符合的第一条数据
         *
         * @param obj
         *            数据对象
         * @param findKeys
         *            查询条件 key
         * @param findValues
         *            查询条件 value
         * @param collectionName
         *            集合名
         * @return
         */
    public static Object findOne(Object obj, String[] findKeys, Object[] findValues, String collectionName) {

        Criteria criteria = null;
        for (int i = 0; i < findKeys.length; i++) {
            if (i == 0) {
                criteria = Criteria.where(findKeys[i]).is(findValues[i]);
            } else {
                criteria.and(findKeys[i]).is(findValues[i]);
            }
        }
        Query query = Query.query(criteria);
        Object resultObj = mongodbUtils.mongoTemplate.findOne(query, obj.getClass(), collectionName);
        return resultObj;
    }

    /**
         * 查询出所有结果集 集合为数据对象中 @Document 注解所配置的collection
         *
         * @param obj
         *            数据对象
         * @return
         */
    public static List<? extends Object> findAll(Object obj) {

        List<? extends Object> resultList = mongodbUtils.mongoTemplate.findAll(obj.getClass());
        return resultList;
    }

    /**
         * 查询出所有结果集 集合为数据对象中 @Document 注解所配置的collection
         * @param clazz
         * @param <T>
         * @return
         */
    public static <T>  List<T> findAll(Class<T> clazz){
        List<T> resultList = mongodbUtils.mongoTemplate.findAll(clazz);
        return resultList;
    }

    /**
         * 指定集合 查询出所有结果集
         *
         * @param obj
         *            数据对象
         * @param collectionName
         *            集合名
         * @return
         */
    public static List<? extends Object> findAll(Object obj, String collectionName) {

        List<? extends Object> resultList = mongodbUtils.mongoTemplate.findAll(obj.getClass(), collectionName);
        return resultList;
    }

    /**
         * 指定集合 查询出所有结果集
         * @param clazz
         * @param collectionName
         * @param <T>
         * @return
         */
    public static <T> List<T> findAll(Class<T> clazz, String collectionName) {
        List<T> resultList = mongodbUtils.mongoTemplate.findAll(clazz, collectionName);
        return resultList;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值