[TOC]

【 Mongo series 】mongodb learning ii, the basic use of mongodb comb

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

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

Basic Concepts of mongodb

  • The document

Is the smallest data set unit of mongodb, and is a data unit of ordered tenants of multiple key-value pairs, similar to the records of a relational database

  • A collection of

A collection of documents, documents store data, the structure of the collection can be different, the collection is similar to the table of a relational database

  • library

A database consisting of multiple collections. Each database city is completely independent, with its own users, permissions, and separate storage folders

  • The instance

In the system runtime process and node set, an instance can have multiple databases

Compare relational databases with mongodb

For example, compare mongodb with mysql

The file name MongoDB Mysql
The service name mongod mysqld
The client name mongo mysql

Open source database components like this have a D after the service name

The client program is used to communicate with the server program

Relational database and mongodb basic concept comparison learning

concept Relational database Mongdb
The database database database
table table collection
The data line row data document
field column field
The index index index
A table join Embedding or linkding
Sharding/partitioning partition shard
The partitioning key partition key sharding key

In the above table, we can clearly see that the documents in mongodb correspond to the row data of the relational database, and the sets in mongodb correspond to the tables of the relational database

The data type of mongodb

As mentioned in the previous figure, documents in mongodb are similar to JSON objects and belong to one type of JSON called BSON.

The values in the fields in the document can include other documents, known as inline documents, as well as arrays and document data

The advantages of document storage are as follows:

  • The document

Objects, which correspond to native data types in many programming languages

  • Embedded documents and arrays reduce the need for connections
  • Dynamic patterns support smooth polymorphism

Bson is a binary representation of a JSON document. Bson contains more data types than JSON:

type number instructions
Double 1 A double precision floating point value
String 2 String, utF-8 is valid
Object 3 For inline documents
Array 4 An array of
Binary data 5 Binary data
Udefined 6 “Undefined”
Objectid 7 The object id
Boolean 8 Boolean
Date 9 Date time, Unix standard
Null 10 Create an empty value
Regular Expression 11 Regular expression
DBPointer 12 “DbPointer”
JavaScript 13 “Javascript”
Symbol 14 “Symbol”
JavaScript (with Scope) 15 “Javascript with scope”
32 – bit integer 16 The int type
Timestamp 17 Special internal types used by mongodb replication and sharing where the first 4 bytes are deltas and the next 4 bytes are timestamps
64-bit integer 18 long
Decimal128 19 decimal
Min key – 1 Types with values lower than normal Bson elements have the same effect as 255
Max key 127 A type with a value higher than normal Bson type elements

One thing to note:

The maximum size of a BSON document is 16M, and the document nesting level cannot exceed 100 layers

See if this contradicts mongodb’s ability to store large amounts of data in terabytes or petabytes, but let’s look at this data type

GridFS

Docs.mongodb.com/manual/core…

GridFS data types are used for storing and retrieving data that exceeds the bson-document size limit (16mb)

Simple installation of mongodb

The installation of mongodb will not be described here, but you can check out my history article to see how to install and use mongodb in GO

Basic command usage of mongodb

This section describes common mongodb commands

The command role
Use database name If the database does not exist, create it; if it does exist, use it
show dbs Display database
db.dropDatabase() Deleting the current database
Db. Set name. Drop () Delete the collection
Db.createcollection (” Collection name “) Create a collection
Db. Set name. Insert ({}) If the collection does not exist, the data is created and inserted by default

If the collection exists, the data is inserted
show collections / show tables Displays a collection of current data
Db. Set name. InsertOne ({}) Insert a piece of data
Db. Set name. InsertMany ({[]}) Insert multiple data
Db. Set name. Find () Find all data in the current table
Db. Collection name. Update ({condition},{update operation to be done}) Update document data
Db.collection. save({with data in Objectid}) Replace existing documents with an update if the Objectid primary key exists and insert if it does not
db.collection.remove({}) Delete the document
Db. Set name. Find ().pretty() Output in a friendlier way

Precautions for creating a new document:

  • When you create a new document, it automatically creates a collection, a database that doesn’t exist
  • If you do not specify a primary key, the primary key _id and its value are automatically generated
  • Write operations are basically atomic operations at the single document level

For mongo DB query operations, we can use the following operators

The operator instructions
$eq Is equal to the
$lt Less than
$lte Less than or equal to
$gt Is greater than
$gte Greater than or equal to
$in Checks whether the element is in the specified collection range
$all Check whether an array contains a certain number of elements, regardless of order
$nin Checks if an element is not in the specified collection range
$ne Is not equal to
$not Mismatched result
$or Matches if one condition is true
$nor So none of the conditions match
$and All conditions must match
$exists Determines whether the element exists
. Subdocument matching
$regex Regular expression matching

Additional actions for mongodb queries:

  • Select the fields you want

Find ({},{field name :1})

  • Exclude fields that are not needed

Find ({},{field name :0})

  • Selection of array child elements

Find ({},{” field name. {$slice:[1,2]})

$slice, which can take an array of two elements, representing a skip number and a limit number

  • The sorting

sort()

Find ().sort({” 表 名 “:1})

1 is ascending

2 is descending

  • Skip and restrict

Skip (n), skip n data

Limit (n) : limits n data

Find ().skip(3).limit(2)

  • Query for unique values

Db.set name.find ().distinct({” field name “})

For the time being, the above operations are often used. For the time being, we will first sort out the operations here, and then continue to write the others in the next article. About the above operations, we still need to go through them by ourselves, think and compare with our own brain, so that we can get familiar with them quickly, and we can use them quickly when we really need them

Welcome to like, follow and favorites

Friends, your support and encouragement, I insist on sharing, improve the quality of the power

All right, that’s it for this time

Technology is open, our mentality, should be more open. Embrace change, live in the sun, and strive to move forward.

I am Nezha, welcome to like, see you next time ~