MongoDB初体验

  |   0 评论   |   312 浏览

前言

对于一个零基础的同学,快速上手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" }

参考

评论

发表评论

validate