2019 MongoDB 入门教程: mongodb安装部署 + 使用mongo命令、java、spring data mongodb增删改查

2019 MongoDB 入门教程

欢迎转载,转载请注明网址:https://blog.csdn.net/qq_41910280

简介:一篇入门级别MongoDB教程。

1. MongoDB安装

Windows:
进入bin目录下
mongod --dbpath D:\develop\MongoDB\data\db --logpath " D:\develop\MongoDB\data\logs\mongo.log " --logappend
管理员cmd添加服务:
mongod --dbpath “D:\develop\MongoDB\data\db” --logpath “D:\develop\MongoDB\data\logs\mongo.log” --logappend --install --serviceName “MongoDB”
之后执行命令(管理员): net start MongoDB
删除服务
mongod --remove --serviceName “MongoDB”

Linux:
进入bin目录下 可选: export PATH=$PATH:/usr/local/mongodb/bin
查看版本 ./mongo -version
创建mongo.cfg文件

dbpath=/usr/local/mongodb/data/db
logpath=/usr/local/mongodb/data/logs/mongodb.log
#后台运行
fork=true
bind_ip=0.0.0.0
logappend=true

首先, 将bind_ip改为0.0.0.0 (让其他电脑可以访问,用于远程连接,如果bind_ip是127.0.0.1的话,就只能本地访问)
配置文件启动 mongod -f /usr/local/mongodb/bin/mongo.cfg
停止 ./mongod -shutdown -dbpath=/usr/local/mongodb/data/db
连接 ./mongo

cmd启动 ./mongod -dbpath=/usr/local/mongodb/data/db -logpath=/usr/local/mongodb/data/logs/mongodb.log -logappend -port=27017 -fork # 不修改bind_ip 远程无法访问
常用的启动参数:
–dbpath:指定存储数据的文件夹
–logpath:指定日志存储文件
–logappend:日志以增加方式产生
–port指定端口,如果不写的话,默认是27017
–fork代表后台运行

2. mongo命令CRUD

  使用 mongo IP:port 连接mongo server(不指定IP端口默认连接127.0.0.1:27017)
在这里插入图片描述
2.1 基本命令
show dbs 展示mongodb中的数据库
use dbname 切换或创建数据库
show collections 展示当前数据库中的集合

2.2 增加文档
db.collection.save(bson) 保存bson对象到collection // 如果collection不存在会自动创建
在这里插入图片描述

2.3 查询文档
db.collection.find() 查询全部数据
在这里插入图片描述
其中_id相当于主键, 如果我们没有指定该字段, mongodb会自动生成
提示: 使用db.help()或db.collection.help()或db.collection.find().help()命令打开帮助
查询电话是12222222222的数据, 注意字段类型
在这里插入图片描述
还有findOne()只查询一条记录
limit()限制结果数量

2.4 修改文档
在这里插入图片描述
原来的孙悟空只剩下_id 和age两个字段了
如何保留其他字段呢?
通过$set
在这里插入图片描述
这些命令不用记, 我都是猜的, 猜不出来的命令不是好命令

2.5 删除文档
在这里插入图片描述
附:
测试数据

db.user.save({name:"沙和尚",sex:"男",age:25,address:"流沙河路11号"});
db.user.save({name:"唐僧",sex:"男",age:35,address:"东土大唐"});
db.user.save({name:"白骨精",sex:"女",age:18,address:"白骨洞"});
db.user.save({name:"白龙马",sex:"男",age:20,address:"西海"});
db.user.save({name:"哪吒",sex:"男",age:15,address:"莲花湾小区"});

2.6 高级查询
模糊查询
MongoDB的模糊查询是通过正则表达式的方式实现的。格式为:
/模糊查询字符串/
如果要查询name字段中以“白”开头的,代码如下:
在这里插入图片描述
大于小于不等于
db.collection.find({ “field” : { $gt: value } } ); // 大于: field > value
db.collection.find({ “field” : { $lt: value } } ); // 小于: field < value
db.collection.find({ “field” : { $gte: value } } ); // 大于等于: field >= value
db.collection.find({ “field” : { $lte: value } } ); // 小于等于: field <= value
db.collection.find({ “field” : { $ne: value } } ); // 不等于: field ≠ value

判断字段是否存在
$exists
示例:查询所有含有address字符的文档
在这里插入图片描述
示例:查询所有不含有address字符的文档
在这里插入图片描述

包含与不包含
包含使用$in操作符。
示例:查询student集合中age字段包含20,25,30的文档
在这里插入图片描述
示例:查询student集合中age字段不包含20,25,30的文档
在这里插入图片描述
统计记录条数
count()

条件连接
并且: $and   或者: $or
示例:查询student集合中age大于等于20 并且age小于30的文档
在这里插入图片描述
查询student集合中sex为女,或者年龄小于20的文档记录
在这里插入图片描述

3. Java连接MongoDB

https://github.com/Spark4J/mongodb-demo

4. spring-data-mongodb

springboot 2.1.3 ( spring-data-mongodb 2.1.5 )
pom.xml

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

实体类

package com.example.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Data
@NoArgsConstructor
@AllArgsConstructor
//@Document("customer")// 不指定collection默认是customer
public class Customer {
    @Id
    public String id;
    public String firstName;
    public String lastName;

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

DAO

package com.example.dao;

import com.example.domain.Customer;
import org.springframework.data.mongodb.repository.MongoRepository;

import java.util.List;

public interface CustomerRepository extends MongoRepository<Customer, String> {
    public Customer findByFirstName(String firstName);
    public List<Customer> findByLastName(String lastName);
}

Test

package com.example;

import com.example.dao.CustomerRepository;
import com.example.domain.Customer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
    @Autowired
    private CustomerRepository repository;

    @Test
    public void contextLoads() {
        repository.deleteAll();

        // save a couple of customers
        repository.save(new Customer("Alice", "Smith"));
        repository.save(new Customer("Bob", "Smith"));

        // fetch all customers
        System.out.println("Customers found with findAll():");
        System.out.println("-------------------------------");
        for (Customer customer : repository.findAll()) {
            System.out.println(customer);
        }
        System.out.println();

        // fetch an individual customer
        System.out.println("Customer found with findByFirstName('Alice'):");
        System.out.println("--------------------------------");
        System.out.println(repository.findByFirstName("Alice"));

        System.out.println("Customers found with findByLastName('Smith'):");
        System.out.println("--------------------------------");
        for (Customer customer : repository.findByLastName("Smith")) {
            System.out.println(customer);
        }

    }

}

结果

Customers found with findAll():
-------------------------------
Customer(id=5ca428dfcbd6cd0614c11211, firstName=Alice, lastName=Smith)
Customer(id=5ca428dfcbd6cd0614c11212, firstName=Bob, lastName=Smith)

Customer found with findByFirstName('Alice'):
--------------------------------
Customer(id=5ca428dfcbd6cd0614c11211, firstName=Alice, lastName=Smith)
Customers found with findByLastName('Smith'):
--------------------------------
Customer(id=5ca428dfcbd6cd0614c11211, firstName=Alice, lastName=Smith)
Customer(id=5ca428dfcbd6cd0614c11212, firstName=Bob, lastName=Smith)

在这里插入图片描述


是不是意犹未尽 ~ ↓↓↓
  点击成为砖(guang)家(tou)... (逃




参考文献

  1. spring guide
  2. 传智mongoDB_课程讲义_1.0



神奇的小尾巴:
本人邮箱:[email protected] [email protected]
[email protected] 欢迎交流,共同进步。
欢迎转载,转载请注明本网址。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章