前言
对于一个零基础的同学,快速上手 MongoDB。
命令快速查看
查看所有库
show dbs;
查看当前库
db
切换对应库
切换到 admin
use admin;
查看所有表
show collections
客户端使用初体验
连接数据库
mongo mongodb://username:password@host:port/dbname
连接成功后的提示:
MongoDB shell version v3.4.10
connecting to: mongodb://username:password@host.mongodb.rds.aliyuncs.com:3717/dbname
MongoDB server version: 3.4.6
创建一张表
创建表 user
> db.createCollection('user')
{ "ok" : 1 }
写入测试数据
> db.user.insert({"name":"note","age":"28"});
WriteResult({ "nInserted" : 1 })
> db.user.insert({"name":"www","age":"20"});
WriteResult({ "nInserted" : 1 })
查看所有表
> db.getCollectionNames();
[ "user" ]
查看某一张表的数据
假如表名为 user
> db.user.find()
{ "_id" : ObjectId("5bb083fb47941b29a337209d"), "name" : "note", "age" : "28" }
{ "_id" : ObjectId("5bb0841647941b29a337209e"), "name" : "www", "age" : "20" }
使用 Springboot 操作 mongodb
pom.xml
自动生成即可。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
创建表 User
package com.example.testmongodb.model;
import org.springframework.data.annotation.Id;
public class User {
@Id
public String id;
public String name;
public String age;
public User() {}
public User(String name, String age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}
}
实现 Mongo 接口
package com.example.testmongodb.repository;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.example.testmongodb.model.User;
public interface UserRepository extends MongoRepository {
public User findByName(String name);
public List findByAge(String age);
}
增加 Controller 来测试结果
package com.example.testmongodb.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.testmongodb.model.User;
import com.example.testmongodb.repository.UserRepository;
@RestController
public class MongodbController {
@Autowired
UserRepository userRepository;
@GetMapping(value = "/")
public String get() {
List<User> stringList = userRepository.findAll();
return stringList.toString();
}
}
配置
修改 application.properties
值为:
spring.data.mongodb.uri=mongodb://username:password@host.mongodb.rds.aliyuncs.com:3717/dbname
运行
$ curl "localhost:8080/"
[User{id='5bb083fb47941b29a337209d', name='note', age='28'}, User{id='5bb0841647941b29a337209e', name='www', age='20'}]
GridFS 使用体验
GridFS 是基于 Mongodb 实现的文件存储系统,适用于大小超过 16MB 的文件。
默认情况下,会把文件拆分成 255k 大小的 chunks (parts),每个 chunk 做为一个 document,chunks 之间保持有序。
同时,文件的元信息(metadata), 包括文件的属性、文件名、文件类型等,会同时保存到另一个 Collection 中。
因为 mongodb 中单 document 的大小上限为 16MB,所以存储超过 16MB 的文件时,就需要用 GridFS 了。GridFS 可以做到支持数 G 的文件,读取时可以按段读取。
基本用法
- list - list all files; 'filename' is an optional prefix which listed filenames must begin with
- search - search all files; 'filename' is a substring which listed filenames must contain
- put - add a file with filename 'filename'
- get - get a file with filename 'filename'
- get_id - get a file with the given '_id'
- delete - delete all files with filename 'filename'
- delete_id - delete a file with the given '_id'
上传文件
mongofiles -d gridfs put sample.wav
结果
2018-10-27T22:08:03.541+0800 connected to: localhost
added file: sample.wav
下载文件
mongofiles -d gridfs get sample.wav
结果
2018-10-27T22:18:48.254+0800 connected to: localhost
finished writing to sample.wav
根据 id 下载文件
mongofiles -d gridfs get_id 'ObjectId("5bd471432b95d111c2da3f38")'
结果
2018-10-27T22:41:49.113+0800 connected to: localhost
2018-10-27T22:41:49.114+0800 found file 'sample.wav' with _id ObjectId("5bd471432b95d111c2da3f38")
finished writing to: sample.wav
文件列表
mongofiles -d gridfs list
结果
2018-10-27T22:25:50.051+0800 connected to: localhost
sample.wav 121940
根据 id 删除文件
mongofiles -d gridfs delete_id 'ObjectId("5bd471432b95d111c2da3f38")'
结果
2018-10-27T22:42:43.897+0800 connected to: localhost
successfully deleted file with _id ObjectId("5bd471432b95d111c2da3f38") from GridFS
在 mongo 中查询
进入 mongo
mongo gridfs
查看
> db.fs.files.find()
结果
{ "_id" : ObjectId("5bd471432b95d111c2da3f38"), "chunkSize" : 261120, "uploadDate" : ISODate("2018-10-27T14:08:03.544Z"), "length" : 121940, "md5" : "dc67d6d74d1599faf073d3f27bf6f855", "filename" : "sample.wav" }
根据 id 查找
> db.fs.files.find({"_id":ObjectId("5bd471432b95d111c2da3f38")})
结果
{ "_id" : ObjectId("5bd471432b95d111c2da3f38"), "chunkSize" : 261120, "uploadDate" : ISODate("2018-10-27T14:08:03.544Z"), "length" : 121940, "md5" : "dc67d6d74d1599faf073d3f27bf6f855", "filename" : "sample.wav" }
磁盘问题
mongodb 有一个问题,即删除其中的文件后,磁盘空间不会释放到操作系统中。怎么办呢?
这块儿我也没有想清楚,目前有两个思路:
一个是:
> use gridFS
switched to db gridFS
> db.runCommand({compact:"fs.chunks"})
{ "ok" : 1 }
> db.runCommand({compact:"fs.files"})
{ "ok" : 1 }
另一个是:
> use gridFS
switched to db gridFS
> db.repairDatabase()
{ "ok" : 1 }
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于