Beginners learn the basics of Mongodb

Beginners learn the basics of Mongodb

Relational and non-relational databases

For relational databases, tables and databases must be created before storing data. As the complexity of the data becomes higher and higher, the number of tables built increases.
However, non-relational databases do not need to be so complicated.

1. Introduction to Mongodb

MongoDB is written in C++ language and is an open source database system based on distributed file storage . MongoDB stores data as a document, and the data structure consists of key-value (key=>value) pairs. MongoDB documents are similar to JSON objects. Field values ​​can contain other documents, arrays, and document arrays.

2. Mongodb installation

2.1 window system

step 1: Download the installation package

Download from the official website: https://www.mongodb.com/try/download/community

Insert image description here
step 2: Double-click to install -----》》Click next-----》》Select Custom ----》》You can customize the installation path or the default installation path. ----》》Finally, uncheck the default compass.
Insert image description here

step 3: Create a storage location for the database file

Create data under MongoDB and create db under data:c:\data\db

Because you need to create the storage folder for the database file before starting the mongodb service, otherwise the command will not be automatically created and the startup will not be successful.

step 4: Start the service

  • Double-click Mongoddb–》》Service —》》 4.2 —》》bin —》》mongod.exe

  • In the bin directory—enter the command—cmd----》》mongod --dbpath c:\data

Insert image description here
stpe 5: Enter http://localhost:27017 on the browser

Insert image description here

connection succeeded!

If the installation is successful and the command execution in the bin directory is unsuccessful, configure the environment variables:

Insert image description here

Configure the path in the same way as configuring the java environment.%MONGODB_HOME%\bin

2.2 Linux system

step1: Upload----/opt/sofware

step2: Unzip:tar -zvxf mongodb-linux-x86_64-amazon-4.2.7.tgz

step3: change the namemv mongodb-linux-x86_64-amazon-4.2.7 mongodb

step 4: Configure environment variables and configuration files:

Enter in the mongodb directory: vi /etc/profile

join in:export PATH=/usr/local/mongodb/bin:$PATH

step 5: Create:mkdir /usr/local/mongodb

Step 6: MongoDB data is stored in the db directory of the data directory, but this directory will not be automatically created during the installation process, so you need to manually create the data directory, and create the db directory and log files in the data directory.

mkdir -p /data/db mkdir -p /logs

Step 7: Copy the downloaded bin directory of mongodb to the set path, which /usr/local/mongodb/binis

Change directory tocd /usr/local/mongodb

Copy filescp -r /opt/softeware/mongodb/bin/ ./

step 8: Create the mongodb.conf file in the bin directory. It is a new file and we need to fill it in.

# 数据文件存放目录
dbpath = /data/db
# 日志文件存放目录
logpath = /logs/mongodb.log 
# 端口
port = 27017
# 以守护程序的方式启用,即在后台运行
fork = true
# 需要认证。如果放开注释,就必须创建MongoDB的账号,使用账号与密码才可远程访问,第一次安装建议注释
# auth=true 
# 允许远程访问,或者直接注释,127.0.0.1是只允许本地访问
bind_ip=0.0.0.0 

"esc" ":" "wq" # 保存退出

step 8: Start the service

./mongod -f mongodb.conf

step9: Enter the mongodb database

./mongo

step 10: View the process:netstat -nplt

Two ways to shut down the mongodb service

​ Kill the process: kill -9 pid

​ ./mongod --shutdown

3. Characteristics of mongodb

  • MongoDB is a database for document storage, which is relatively simple and easy to operate.
  • You can set the index on any attribute in the MongoDB record (eg: FirstName="Sameer", Address="8 Gandhi Road") to achieve faster sorting.
  • You can create data mirrors locally or over the network, which makes MongoDB more scalable.
  • If the load increases (more storage space and more processing power are required), it can be distributed across other nodes in the computer network. This is called sharding.
  • Mongo supports rich query expressions. The query command uses tags in JSON format to easily query objects and arrays embedded in the document.
  • MongoDb uses the update() command to replace the completed document (data) or some specified data fields.
  • Map/reduce in Mongodb is mainly used for batch processing and aggregation of data.
  • Map and Reduce. The Map function calls emit(key, value) to traverse all the records in the collection, and passes the key and value to the Reduce function for processing.
  • Map functions and Reduce functions are written in Javascript and can perform MapReduce operations through db.runCommand or mapreduce commands.
  • GridFS is a built-in feature in MongoDB that can be used to store a large number of small files.
  • MongoDB allows scripts to be executed on the server side. You can write a function in Javascript and execute it directly on the server side. You can also store the function definition on the server side and call it directly next time.
  • MongoDB supports various programming languages: RUBY, PYTHON, JAVA, C++, PHP, C# and other languages

4. Common database commands of Mongodb

创建数据库
use rundo

查看当前数据库: 
db

查看所有的数据库: 
show dbs 或者 show databases

切换数据库: 
use db_name

删除当前数据库:
db.dropDatabase()

After creating the database, checking all databases shows that the database you just created is not there because you have no data in it.

 db.rundo.insert({
   
   "name":"zhangsan"})

When querying all databases, the database you just created will be displayed.

5. Mongodb collection command

If you do not create a collection manually, the collection will be automatically created the first time you add data to a collection that does not exist.

-- 创建集合
db.createCollection(name,options)

-- 查看集合
show  collections

-- 删除已有集合
-- 如果成功删除选定集合,则 drop() 方法返回 true,否则返回 false。

db.Collection_name.drop()

Parameter Description

  • name: the name of the collection to be created
  • options: optional parameters, specify options related to memory size and index

Parameters in options:

Field type describe
capped Boolean (Optional) If true, creates a fixed collection. A fixed collection is a collection with a fixed size that automatically overwrites the oldest document when the maximum size is reached.
When this value is true, the size parameter must be specified.
autoIndexId Boolean 3.2 之后不再支持该参数。(Optional) If true, automatically create an index on the _id field. Default is false.
size numerical value (Optional) Specify a maximum value in kilobytes (KB) for the fixed collection.
If capped is true, this field also needs to be specified.
max numerical value (Optional) Specifies the maximum number of documents included in the fixed collection.

When inserting a document, MongoDB first checks the size field of the fixed collection and then checks the max field.

-- 创建数据库test
use test

-- 在test里创建student集合
db.createCollection("student")

db.createCollection("stu",{capped : true ,autoIndexId : true, size: 6000, max : 10 })


-- 删除已有集合
db.stu.drop();

6. Common data types in mongodb

  1. Object ID: ⽂档ID
  2. String: String, most commonly used, must be valid UTF-8
  3. Boolean: Stores a Boolean value, true or false
  4. Integer: Integers can be 32-bit or 64-bit, depending on the server
  5. Double: Stores floating point values
  6. Arrays: Arrays or lists, multiple values ​​stored to one key
  7. Object: used for embedded documents, that is, one value is a document
  8. Null: Store Null value
  9. Timestamp: timestamp, indicating the total number of seconds from 1970-1-1 to the present
  10. Date: UNIX time format that stores the current date or time

7. Mongodb adds data to the collection (insert document)

The data structure of the document is basically the same as JSON. All data stored in the collection is in BSON format.

Introduction to BSON

BSON is based on the JSON format and is a computer data exchange format. It is mainly used as a data storage and network transmission format in the MongoDB database. It is a binary representation that can be used to represent simple data structures, associative arrays (called "objects" or "documents" in MongoDB), and various data types in MongoDB.

BSON features

Lightweight, traversable, and efficient.

  • Faster traversal speed

  • Easier to operate

  • Additional data types added

7.1 MongoDB uses inserting documents into a collection

db.COLLECTION_NAME.insert(document)
db.COLLECTION_NAME.save(document)

save(): If the _id primary key exists, update the data, and if it does not exist, insert the data. This method has been deprecated in the new version and can be replaced by db.collection.insertOne() or db.collection.replaceOne().
insert(): If the primary key of the inserted data already exists, an org.springframework.dao.DuplicateKeyException exception will be thrown, indicating that the primary key is duplicated and the current data will not be saved.

-- 插入单条数据
db.student.save({name:'liunana',gander:'女',age:18})

db.student.insert({name:'zhangsan',gander:'男',age:18})

-- 插入多条数据
db.student.insert([{name:'zhangsan',gander:'男',age:18},{name:'qq',gander:'女',age:20}])
-- 将数据定义为一个变量
doc = ({name:'lisi',gander:'男',age:18})
db.student.insertOne(doc)

7.2 Mongodb query documents

db.student.find()Query all documents

parameter

query: optional, use query operator to specify query conditions

projection: Optional, use the projection operator to specify the returned keys. To return all key values ​​in the document when querying, just omit this parameter (omitted by default).

db.student.findOne()Only return the first piece of data

db.student.find({condition})Conditional query

db.student.find({gander:'男'})

pretty()Format document

7.2.1 Comparison of mongodb query conditions and RDBMS condition queries
operate Format example Similar statements in RDBMS
equal {<key>:<value>} db.col.find({"by":"菜鸟教程"}).pretty() where by = '菜鸟教程'
less than {<key>:{$lt:<value>}} db.col.find({"likes":{$lt:50}}).pretty() where likes < 50
less than or equal to {<key>:{$lte:<value>}} db.col.find({"likes":{$lte:50}}).pretty() where likes <= 50
more than the {<key>:{$gt:<value>}} db.col.find({"likes":{$gt:50}}).pretty() where likes > 50
greater than or equal to {<key>:{$gte:<value>}} db.col.find({"likes":{$gte:50}}).pretty() where likes >= 50
not equal to {<key>:{$ne:<value>}} db.col.find({"likes":{$ne:50}}).pretty() where likes != 50
7.2.2 MongoDB AND conditions

MongoDB's find() method can pass in multiple keys, each key separated by commas, which is the AND condition of conventional SQL.

db.col.find({key1:value1, key2:value2}).pretty()
db.student.find({
   
   'name':'zhangsan','gander':'男'})

7.3 mongodb update document

update()behind the method

  • upsert : Optional, this parameter means whether to insert objNew if there is no updated record, true means insert, the default is false, not insert.
  • multi : optional. The default value of mongodb is false. Only the first record found will be updated. If this parameter is true, all multiple records found according to the conditions will be updated.
  • writeConcern : Optional, the level at which the exception is thrown.

Insert several pieces of data into the rundo collection

db.rundo.insert([{
    '_id': '1',
    'title': 'java',
    'desc': 'Java编程'
}, {
    '_id': '2',
    'title': 'php',
    'desc': 'php编程'
}, , {
    '_id': '3',
    'title': '.net',
    'desc': '.net编程'
}, {
    '_id': '4',
    'title': 'java',
    'desc': 'java编程'
}, {
    '_id': '5',
    'title': 'java',
    'desc': 'java编程'
}])

Modify java to Java

db.rundo.update({ 'title': 'java'}, {$set:{
   
   'title':'Java'}})

The first piece of data found is modified. If you modify data in batches, multichange the value to true

db.rundo.update({ 'title': 'java'}, {$set:{
   
   'title':'Java'}},{multi:true})

7.4 mongodb delete document

The remove() function is used to remove data from the collection.

db.collection.remove(<query>,{justOne: <boolean>,writeConcern: <document>})

query: (optional) Conditions for deleted documents.
justjOne: (Optional) If set to true or 1, only one document will be deleted. If this parameter is not set, or the default value of false is used, all documents matching the condition will be deleted.
writeConcern: (optional) The level at which the exception is thrown.

-- 两种写法
db.rundo.remove({
   
   'title':'Java'},1)
db.rundo.remove({
   
   'title':'Java'},{justjOne:true})

7.5 MongoDB relationships

MongoDB relationships represent the logical interconnections between multiple documents.

Method: Embed and quote

  • 1:1 (1 to 1)
  • 1: N (1 to many)
  • N: 1 (many to 1)
  • N: N (many to many)

7.6 mongodb sorting

sort()method

-- 升序
db.student.find().sort({
   
   key:1}) 
-- 降序
db.student.find().sort({
   
   key:-1})

7.7 MongoDB index

createIndex()method

db.collection.createIndex(keys, options)

The Key value is the index field you want to create. 1 means to create the index in ascending order. If you want to create the index in descending order, specify -1.

db.student.createIndex({
   
   'title':1})

7.8MongoDB Aggregation

aggregate()method

db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
expression describe
$sum Calculate the sum.
$avg Calculate average
$min Get the minimum value corresponding to all documents in the collection.
$max Get the maximum value corresponding to all documents in the collection.
$push Insert values ​​into an array in the resulting document.
$addToSet Inserts values ​​into an array in the resulting document, but does not create a copy.
$first Get the first document data based on the sorting of resource documents.
$last Get the last document data based on the sorting of resource documents
db.rundo.insert([{
   _id: 1,
   title: 'MongoDB Overview', 
   description: 'MongoDB is no sql database',
   by_user: 'runoob.com',
   url: 'http://www.runoob.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100
},
{
   _id: 2,
   title: 'NoSQL Overview', 
   description: 'No sql database is very fast',
   by_user: 'runoob.com',
   url: 'http://www.runoob.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 10
},
{
   _id: 3,
   title: 'Neo4j Overview', 
   description: 'Neo4j is no sql database',
   by_user: 'Neo4j',
   url: 'http://www.neo4j.com',
   tags: ['neo4j', 'database', 'NoSQL'],
   likes: 750
}])
-- 总和
db.rundo.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])
-- 相当于关系型数据库的
 select by_user, count(*) from rundo group by by_user
-- 平均值
db.rundo.aggregate([{$group : {_id : "$by_user", num_tutorial : {$avg : "$likes"}}}])
-- 对应的关系型数据库
select by_user,avg(likes) from rundo group by by_user
-- 最小值
db.mycol.aggregate([{$group : {_id : "$by_user", min : {$min : "$likes"}}}])
-- 对应的关系型数据库
select by_user,min(likes) from rundo group by by_user
-- 最大值
db.rundo.aggregate([{$group : {_id : "$by_user", max : {$max : "$likes"}}}])
-- 对应的关系型数据库
select by_user,max(likes) from rundo group by by_user
-- 根据条件找的最后一条
db.rundo.aggregate([{$group : {_id : "$by_user", last_url : {$last : "$url"}}}])
-- 根据条件找每组的第一条
db.rundo.aggregate([{$group : {_id : "$by_user", last_url : {$last : "$url"}}}])

8. Integrate mongodb in springboot

rely

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

Connect to the database

spring:
  data:
     mongodb:
      host: 127.0.0.1
      port: 27017
      # 数据库名
      database: user

Write entity layer

package com.xinzhi.springmon.entity;

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

import java.io.Serializable;
import java.util.Date;

/**
 * @author ch
 * @date 2020/7/11
 */
@Document
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
    
    
    @Id
    private Integer id;

    private String username;
    private Integer age;
    private Date createTime;
    private Date updateTime;
}

If the lombok plug-in is not introduced, the getting and setting of the entity layer must be created manually.

service layer

package com.xinzhi.springmon.service;

import com.xinzhi.springmon.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.stereotype.Service;

import java.awt.print.Book;
import java.util.Date;
import java.util.List;


/**
 * @author ch
 * @date 2020/7/12
 */
@Service
public class UserService {
    
    

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存
     */
    public String saveUser(User user) {
    
    
        user.setCreateTime(new Date());
        mongoTemplate.save(user);
        return "SUCCESS";
    }

    /**
     * 获得所有用户
     */
    public List<User> getAllUser() {
    
    
        return mongoTemplate.findAll(User.class);
    }

    /**
     * 通过id找
     */
    public User getUserById(int id) {
    
    
        /**条件*/
        Query query = new Query(Criteria.where("_id").is(id));
        return mongoTemplate.findOne(query, User.class);
    }

    /**
     * 跟新用户信息
     */
    public String updateUser(User user) {
    
    
        Query query = new Query(Criteria.where("_id").is(user.getId()));
        Update update = new Update().set("username", user.getUsername()).set("age", user.getAge()).set("updateTime", new Date());
        /**upsert 更新对象不存在则去添加*/
        mongoTemplate.upsert(query, update, User.class);
        //updateFirst 更新查询返回结果集的第一条
//        mongoTemplate.updateFirst(query, update, User.class);
        /**updateMulti 更新查询返回结果集的全部*/
//        mongoTemplate.updateMulti(query,update,User.class);
        return "SUCCESS";
    }

    /**
     * 根据id删除
     */
    public String deleteUserById(int id) {
    
    
        User user = getUserById(id);
        mongoTemplate.remove(user);
        return "SUCCESS";
    }
}

controller layer

package com.xinzhi.springmon.controll;

import com.xinzhi.springmon.entity.User;
import com.xinzhi.springmon.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ch
 * @date 2020/7/11
 */
@Controller
@ResponseBody
public class UserController {
    
    

    @Autowired
    private UserService userService;

    @PostMapping("/save")
    public String saveUser(@RequestBody User user) {
    
    
        return userService.saveUser(user);
    }

    @GetMapping("/getAll")
    public List<User> getAll() {
    
    
        return userService.getAllUser();
    }

    @GetMapping("/findOne")
    public User getUserById(@RequestParam int id) {
    
    
        return userService.getUserById(id);
    }

    @PostMapping("/update")
    public String update(@RequestBody User user) {
    
    
        return userService.updateUser(user);
    }

    @GetMapping("/delete")
    public String delUserById(@RequestParam int id) {
    
    
        return userService.deleteUserById(id);
    }
}

After starting PostMan, test one by one

Insert image description here
Insert image description here
There is no need to upload the demos one by one.

Guess you like

Origin blog.csdn.net/weixin_47294072/article/details/107295038