当前位置:网站首页>Mongodb installation and basic operation
Mongodb installation and basic operation
2022-07-06 08:49:00 【look-word】
MongoDB Installation
Use docker install
Download mirroring :
docker pull mongo:4.4.8( recommend , Download the specified version )
docker pull mongo:latest ( Download the latest version by default )
Look at the mirror image :
docker images
- You can see mongo It has been downloaded
Start the mirror :
docker run -d --restart=always -p 27017:27017 --name mymongo -v /data/db:/data/db mongo:4.4.8
- -d Background operation
- –restart=always docker Container start up mongo And start The same is true of shutdown
- -name Specify the name of the container
- -v Bound with a file on the disk
Into the container :
docker exec -it mymongo /bin/bash
Enter into mongo The client of
mongo
MongoDB Concept of analytical
No matter what database we learn we should learn the basic concepts, right , stay mongodb The basic concept is documentation 、 aggregate 、 database , Let's introduce in detail , The following table will help you understand more easily Mongo Some of the concepts in :
SQL The term / Concept | MongoDB The term / Concept | explain / explain |
---|---|---|
database | database | database |
table | collection | Database table / aggregate |
row | document | Data record row / file |
column | field | Data field / Domain |
index | index | Indexes |
table joins | Table joins ,MongoDB I won't support it | |
primary key | primary key | Primary key ,MongoDB Automatically put _id Field sets the primary key |
MongoDB Common operations
(1)Help Check the command prompt
db.help();
(2) Switch / Create database
use test
If the database doesn't exist , Then create the database , Otherwise switch to the specified database
(3) Query all databases
show dbs;
(4) Delete the currently used database
db.dropDatabase();
(5) View currently used databases
db.getName();
(6) Show the current db state
db.stats();
(7) At present db edition
db.version();
(8) View the current db Link machine address
db.getMongo();
Commonly used instructions :
Let's create a database first
use test
1 INSERT( newly added )
Insert into User Collection
db.User.save({name:‘zhangsan’,age:21,sex:true})
Inquire about User All documents in the collection
db.User.find()
2 Remove( Delete )
remove() Used to delete single or all documents , The deleted document cannot be recovered
- Delete all :db.User.remove({})
- Appoint id Delete :db.User.remove(id)
- Specify conditions to delete :db.User.remove({‘name’:‘zhangsan’})
3 UPDATE ( modify )
- first { } Is the condition
- The second brace Is the content that needs to be modified
** Example :**db.User.update({name:“lucy”}, {$set:{age:100, sex:0}})
Update() There are a few parameters to note .
db.collection.update(criteria, objNew, upsert, mult)
criteria: Conditional expressions that need to be updated
objNew: Update expression
upsert: Such as FI The label record does not exist , Whether to insert a new document .
multi: Whether to update multiple documents .
4 QUERY( Inquire about )
4.1 WHERE
stay mongo in How do we use conditional queries ?
** grammar :**db.User.find ({“filed”, value })
Example : db.User.find({name:“ Zhang San ”})
convert to sql : select * form User where name = ‘ Zhang San ’
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-VzK8wRwP-1656833727793)(https://img2022.cnblogs.com/blog/2233272/202207/2233272-20220703110249742-987656105.png)]
4.2 FIELDS
In normal development , You only need to query some fields in a set ? So how can we achieve such a business ?
- first {} Express What conditions to query It's up there where
- the second {} Express To be found field The value is 1
** grammar :**db.User.find ( { } , { “filed” , value })
** Example :**db.User.find( { name : “ Zhang San ” } , { ‘name’ : 1 } )
convert to sql: select name from User where name = ‘ Zhang San ’
5 SORT
stay MongoDB Use in sort() Method to sort the data ,sort() Method can be used to specify the sorting field by parameter , And use 1 and -1 To specify how to sort , among 1 Arrange... In ascending order , and -1 It's for descending order .
** Example :**db.User.find().sort({‘age’:1})
The conversion SQL :select * from User order by age desc
6 Intercept
stay MongoDB Use in limit() Method to read a specified amount of data ,skip() Method indicates the line from which to read
Example : db.User.find().skip(1).limit(2)
Corresponding SQL: select * from User skip 1 limit 2
All the data in the set : There are two of them
The first line starts reading Read to the end of the second line
7 in( contain )
Example : db.User.find({age:{$in:[21,26,32]}})
** The conversion SQL:**select * from User where age in (21, 26, 32)
8 COUNT( The statistical number of rows )
Example : select count(*) from User where age >20
The conversion SQL: db.User.find({age:{$gt:20}}).count()
9 OR ( perhaps )
age yes 20 perhaps 30 All meet the conditions Be similar to |
Example : select * from User where age = 21 or age = 30
The conversion SQL: db.User.find({$or:[{age:21}, {age:30}]})
10 aggregate( polymerization )
MongoDB Middle polymerization (aggregate) It's mainly used to process data ( Such as the statistical average , Make a peace, etc ), And return the calculated data result . It's kind of similar sql Statement count(*)
Insert test data
db.article.insert({title: ‘MongoDB Overview’,description: ‘MongoDB is no sql database’,by_user: ‘runoob.com’,url: ‘http://www.runoob.com’,tags: [‘mongodb’, ‘database’, ‘NoSQL’],likes: 100})
db.article.insert({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})
db.article.insert({title: ‘Neo4j Overview’,description: ‘Neo4j is no sql database’,by_user: ‘Neo4j’,url: ‘http://www.neo4j.com’,tags: [‘neo4j’, ‘database’, ‘NoSQL’],likes: 750})
Common aggregate expressions
expression | describe | Example |
---|---|---|
$sum | Calculate the sum | db.mycol.aggregate([{ KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "by_user", num_tutorial : { s u m : " sum : " sum:"likes"}}}]) |
$avg | Average | db.mycol.aggregate([{ KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "by_user", num_tutorial : { a v g : " avg : " avg:"likes"}}}]) |
$min | Get the minimum value of all documents in the collection . | db.mycol.aggregate([{ KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "by_user", num_tutorial : { m i n : " min : " min:"likes"}}}]) |
$max | Get the maximum value of all documents in the collection . | db.mycol.aggregate([{ KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "by_user", num_tutorial : { m a x : " max : " max:"likes"}}}]) |
$push | Insert values into an array in the result document . | db.mycol.aggregate([{ KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "by_user", url : { p u s h : " push: " push:"url"}}}]) |
$addToSet | Insert values into an array in the result document , But don't create copies . | db.mycol.aggregate([{ KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "by_user", url : { a d d T o S e t : " addToSet : " addToSet:"url"}}}]) |
$first | Get the first document data according to the sorting of resource documents | db.mycol.aggregate([{ KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "by_user", first_url : { f i r s t : " first : " first:"url"}}}]) |
$last | Get the last document data according to the sorting of resource documents | db.mycol.aggregate([{ KaTeX parse error: Expected '}', got 'EOF' at end of input: …roup : {_id : "by_user", last_url : { l a s t : " last : " last:"url"}}}]) |
11 Indexes
Indexing can usually be greatly improved
Query efficiency
, If there is no index ,MongoDB When reading data, you must scanCollection
OfEvery
File and select those records that meet the query conditions . This scanFull set
The query efficiency isVery low
Of , Especially when dealing with large amounts of data , Queries can take tens of seconds or even minutes , The performance of this website isVery deadly
Of .Indexes
Is a special data structure , The index is stored in a collection of data that is easy to read through , An index is an index of a database tableOne or more columns
A structure that sorts the values of .
db.User.createIndex({“name”:1})
In the syntax **name**** The value is the index field that you want to create ,
1** Creates an index in ascending order for the specified , If you want to create the index in descending order specify as -1 that will do
边栏推荐
- Delay initialization and sealing classes
- LeetCode:394. 字符串解码
- @Jsonbackreference and @jsonmanagedreference (solve infinite recursion caused by bidirectional references in objects)
- China high purity silver nitrate Market Research and investment strategy report (2022 Edition)
- MYSQL卸载方法与安装方法
- 同一局域网的手机和电脑相互访问,IIS设置
- Roguelike game into crack the hardest hit areas, how to break the bureau?
- LeetCode:剑指 Offer 48. 最长不含重复字符的子字符串
- poi追加写EXCEL文件
- Variable length parameter
猜你喜欢
Computer cleaning, deleted system files
Unified ordering background interface product description Chinese garbled
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
FairGuard游戏加固:游戏出海热潮下,游戏安全面临新挑战
After PCD is converted to ply, it cannot be opened in meshlab, prompting error details: ignored EOF
【ROS】usb_cam相机标定
Bottom up - physical layer
UML图记忆技巧
Sublime text using ctrl+b to run another program without closing other runs
软件卸载时遇到trying to use is on a network resource that is unavailable
随机推荐
超高效!Swagger-Yapi的秘密
Guangzhou will promote the construction of a child friendly city, and will explore the establishment of a safe area 200 meters around the school
游戏解包的危害及资源加密的重要性
Light of domestic games destroyed by cracking
Computer cleaning, deleted system files
PC easy to use essential software (used)
[embedded] cortex m4f DSP Library
广州推进儿童友好城市建设,将探索学校周边200米设安全区域
LeetCode:剑指 Offer 42. 连续子数组的最大和
[MySQL] limit implements paging
有效提高软件产品质量,就找第三方软件测评机构
Process of obtaining the electronic version of academic qualifications of xuexin.com
What is the role of automated testing frameworks? Shanghai professional third-party software testing company Amway
LeetCode:39. 组合总和
Leetcode: Sword finger offer 42 Maximum sum of continuous subarrays
Bottom up - physical layer
Analysis of the source code of cocos2d-x for mobile game security (mobile game reverse and protection)
Navicat premium create MySQL create stored procedure
Precise query of tree tree
egg. JS project deployment online server