• Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Introduction to the

  • NoSQL = Not Only SQL
  • We are usually familiar with the development of relational database, and MongoDB is a new type of non-relational database.

Usage scenarios

  • NoSQL is used for very large scale data storage, like Google or Facebook for their YogHurt phones with trillions of bits of data per day. These types of data storage do not require fixed patterns and can be scaled horizontally without extra manipulation.

RDBMS vs NoSQL

language summary structured performance
RDBMS Highly organized structured data Structured Query Language Based on the transaction
NoSQL Stands for more than just SQL There is no declarative query language High performance High availability and scalability

Common commands

Basic structure


public class User {
    / / the primary key
    private Long id;
    / / user name
    private String userName;
    / / age
    private Integer age;
    / / gender
    private Boolean sex;
    // Date of birth
    private Date birthDate;
    // School date
    private Date schoolDate;
    / / salary
    private Double salary;
}

Copy the code

The query

Query the value of ID=139758337331900416

SQL mode

select * from user where id=139758337331900416

Conventional query

db.user.find({‘_id’:139758337331900416})

Advanced query

db.user.aggregate(
[
    {
        $match: {
            _id: 139758337331900416}}])Copy the code

Fuzzy query fff5fDD6

SQL mode

select * from user where userName like ‘%fff5fdd6%’;

Conventional query

/ ABC /: full fuzzy matching ABC /^ ABC /: fuzzy matching ABC start /^ ABC $/: query data equal to ABC (re)

db.user.find({‘userName’:/fff5fdd6/});

Advanced query

The main regular expression is written to achieve matching


db.user.aggregate(
[
    {
        $match: {
            'userName': {
                $regex: '.*fff5fdd6'
            }
        }
    }
]
)

Copy the code

Query the data whose age is greater than 1720822682

SQL mode

select * from user where age>1720822682;

Conventional query

db.user.find({‘age’:{‘$gt’:1720822682}});

Advanced query

db.user.aggregate([
  {
    '$match': {
        'age': {
            '$gt': 1720822682}}}]);Copy the code

Descending order by ID

SQL mode

select * from user order by id desc;

Conventional query

db.user.find().sort({‘_id’:-1});

Advanced query

db.user.aggregate([
  {
    $order:{
      _id:- 1}}]);Copy the code

Sort by field part

For example, userName is f21BAD93-bcb2-48A1-9446-d429CFb8a63d in uUID format. In this case, the last part of userName split is d429CFb8a63D.

SQL mode

select * from user order by substr((userName),LENGTH(userName)+1-(locate(‘/’,REVERSE(userName))-1));

Conventional query

A regular query on Mongo can only be a regular operation. You can’t satisfy the demand here. This is where advanced queries aggregate are advanced. He supports our logical operation

Advanced query

In the advanced query, we will find that the only queried fields are the participating fields and the Id fields. How we need to display other fields should be configured in the last project, such as Regions :1 indicates display; The fields are configured in the first project, such as Regions :1 for display. The fields are configured in the first project, such as Regions :1 for display. In the first project, “userName”:”$userName” shows the userName field.


db.user.aggregate(
	[
    {
        $project: {
            "userName":"$userName"."regions": {
                $split: [
                    '$userName',
                    '-'
                ]
            }
        }
    },
    {
        $project: {
            "regions": 1."userName":1."userNameOrder": {
                $arrayElemAt: [
                    "$regions".4
                ]
            }
        }
    },
    {
        $sort: {
            userNameOrder: - 1}}])Copy the code

grouping

Report query is the most common group query. Below, we grouped the information according to the time of admission (specific to the day)

SQL mode

select date_format(schoolData,’%Y-%m-%d’) , count(1) from user group by date_format(schoolData,’%Y-%m-%d’) order by date_format(schoolData,’%Y-%m-%d’);

Conventional query

There is no

Advanced query

db.user.aggregate(
[
    {
        $project: {
            "newSchoolDate": {
                $dateToString: {
                    date: '$schoolDate',
                    format: "%Y-%m-%d"
                }
            }
        }
    },
    {
        $group: {
            "_id": "$newSchoolDate"."count": {
                $sum: 1
            }
        }
    },
    {
        $sort: {
            newSchoolDate: - 1}}])Copy the code

The keyword

Above, we looked at the functions of Mongo through several common cases. Basically SQL can achieve the effect, Mongo can. Let’s take a look at some common functions in Mongo.

$bucket

The bucket function is to segment the table data, and the group above is for the whole table. But sometimes we want a certain range to be counted according to certain rules, and the rest to be counted according to other rules. If we use group, we will use the whole table. But sometimes we want a certain range to be counted according to certain rules, and the rest to be counted according to other rules. If we use group, we will use the whole table. But sometimes we want a certain range to be counted according to certain rules, and the rest to be counted according to other rules. At this time, if we use group, we need to use two commands to solve.


db.user.aggregate(
    [
    {
        $bucket: {
            groupBy: "$age",
            boundaries: [
                1.458972139.1542997977
            ],
            default: 'ooo',
            output: {
                "count": {
                    $sum: 1
                },
                "titles": {
                    $push: "$age"}}}}])Copy the code

The collection $project is used


db.user.aggregate(
[
    {
        $project: {
            "newSchoolDate": {
                $dateToString: {
                    date: '$schoolDate',
                    format: "%Y-%m-%d"
                }
            }
        }
    },
    {
        $bucket: {
            groupBy: "$newSchoolDate",
            boundaries: [
                '2021- 01- 20',
                '2021- 01- 21'
            ],
            default: 'ooo',
            output: {
                "count": {
                    $sum: 1
                },
                "titles": {
                    $push: "$_id"
                },
                "schoolds": {
                    $push: "$newSchoolDate"
                }
            }
        }
    },
    {
        $sort: {
            "_id": - 1}}])Copy the code