当前位置:网站首页>Mongodb common commands of mongodb series
Mongodb common commands of mongodb series
2022-07-03 01:07:00 【smileNicky】
One 、MongoDB Basic operation
1.1、 Software environment preparation
Software environment :
- MongoDB Server5.0.9
- Navicat15.0.28
- RoboMongo 0.9.0
- Window10 System
1.2、MongoDB Connect
MongoDB Connect , Use “username:[email protected]/dbname’” In the form of connection .
Connect to the local database server , Port is the default .
mongodb://localhost
1.3、 Create database
MongoDB Create database Syntax
use DATABASE_NAME
demo: establish test database
use test
If there is no database , Just create the database , No, connect to the specified database
View all databases , Use
show dbs
But then we use show dbs Words , Still can't see the database we created , In fact, we need to add data to the database to see
demo: towards test Insert a row of data into the database
db.test.insert({
"name":"test"})
1.4、 Delete database
MongoDB Delete database Syntax
db.dropDatabase()
However, it is generally necessary to use use Connect to database , Then delete the guidance database
demo: Delete test database
Connect test database
use test
Delete test database
db.dropDatabase()
Delete the collection
demo: Delete test Database coll aggregate
> use test
switched to db runoob
> show tables
coll
> db.coll.drop()
true
> show tables
>
1.5、 Inserted into the document
MongoDB The syntax of inserting a document is roughly like
db.COLLECTION_NAME.insert(document)
demo: towards test Database col Insert document in collection
Method 1
>use test
>db.col.insert({
title: 'MongoDB',
description: 'MongoDB NOSQL',
by: 'test',
url: 'https:',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
})
View the written data col aggregate
db.col.find()
Method 2
Define a document object
document=({
title: 'MongoDB',
description: 'MongoDB NOSQL',
by: 'test',
url: 'https:',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
});
perform , Will define document Object to write data
db.col.insert(document)
1.6、 The new document
save() Method
The grammar is like :
db.collection.save(
<document>,
{
writeConcern: <document>
}
)
Parameter meaning
- document : Document data .
- writeConcern : Optional , The level at which an exception is thrown .
demo: To replace the _id by 56064f89ade2f21f36b03136 Document data
db.col.save({
"_id" : ObjectId("56064f89ade2f21f36b03136"),
"title" : "MongoDB",
"description": 'MongoDB NOSQL',
"by": 'test',
"url": 'https:',
"tags": ['mongodb', 'database', 'NoSQL'],
"likes": 100
})
1.7、 Update the document
Update the document operation syntax, such as :
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
)
Parameter meaning :
- query : update Query criteria for , similar sql update In the query where hinder .
- update : update Object and some updated operators ( Such as , , ,inc…) etc. , It can also be understood as sql update In the query set hinder
- upsert : Optional , This parameter means , If it doesn't exist update The record of , Whether insert objNew,true Insert for , The default is false, Do not insert .
- multi : Optional ,mongodb The default is false, Update only the first record found , If this parameter is zero true, According to the conditions to find out all the records updated .
- writeConcern : Optional , The level at which an exception is thrown .
demo: to update test Database documentation
Use test database
use test
Update document action
db.col.update({
'title':'MongoDB'},{
$set:{
'title':'MongoDB test'}})
Then check whether the document is updated
db.col.find()
Modify multiple identical documents
The appeal situation is to modify a document , If you modify multiple identical documents , You need to set multi Parameter is true.
db.col.update({
'title':'MongoDB'},{
$set:{
'title':'MongoDB test'}},{
multi:true})
You can also use updateMulti
db.col.updateMany({
'title':'MongoDB'},{
$set:{
'title':'MongoDB test'}})
Comprehensive operation :
Only the first record is updated :
db.col.update( {
"count" : {
$gt : 1 } } , {
$set : {
"test2" : "OK"} } );
All updates :
db.col.update( {
"count" : {
$gt : 3 } } , {
$set : {
"test2" : "OK"} },false,true );
Just add the first one :
db.col.update( {
"count" : {
$gt : 4 } } , {
$set : {
"test5" : "OK"} },true,false );
Add all in :
db.col.update( {
"count" : {
$gt : 5 } } , {
$set : {
"test5" : "OK"} },true,true );
All updates :
db.col.update( {
"count" : {
$gt : 15 } } , {
$inc : {
"count" : 1} },false,true );
Only the first record is updated :
db.col.update( {
"count" : {
$gt : 10 } } , {
$inc : {
"count" : 1} },false,false );
1.8、 Delete the document
MongoDB Delete the document as
db.collection.remove(
<query>,
<justOne>
)
MongoDB2.6 The operation of later versions is
db.collection.remove(
<query>,
{
justOne: <boolean>,
writeConcern: <document>
}
)
- query :( Optional ) Conditions for deleted documents .
- justOne : ( Optional ) If it is set to true or 1, Only one document is deleted .
- writeConcern :( Optional ) The level at which an exception is thrown .
demo: Delete title by MongoDB The data of
db.col.remove({
'title':'MongoDB'})
Delete all data in the collection
db.col.remove({
})
1.9、MongoDB Inquire about
MongoDB The query syntax
db.collection.find(query, projection)
- query : Optional , Use the query operator to specify the query criteria
- projection : Optional , Use the projection operator to specify the returned key . Returns all key values in the document when queried , Simply omit the parameter ( The default is omitted ).
Easy to read query
db.col.find().pretty()
except find() Out of the way , One more findOne() Method , It returns only one document .
1.10、MongoDB Conditional operation
MongoDB AND Conditions
Multiple keys can be passed in (key), Each key (key) Separated by commas
db.col.find({
key1:value1, key2:value2}).pretty()
Use and
and in
Example , obtain "col" A series of data in a set :
db.getCollection("col").find({
$and: [{
"SYNC_STATUS": "HANDLED"
}, {
"CODE": {
$in: [
"123456789",
"12345678910"
]
}
}]
}).pretty();
MongoDB OR Conditions
db.col.find(
{
$or: [
{
key1: value1}, {
key2:value2}
]
}
).pretty()
MongoDB AND and OR The joint query
AND and OR A combination of , Similar to the conventional SQL Statement for : ‘where likes>50 AND (by = ‘ course ’ OR title = ‘MongoDB course ’)’
MongoDB Conditional operators
- (>) Greater than : $gt
- (<) Less than : $lt
- (>=) Greater than or equal to : $gte
- (<= ) Less than or equal to : $lte
Demo:
obtain “col” Collection “likes” Greater than 100 The data of , You can use the following command :
db.col.find({
"likes" : {
$gt : 100}})
obtain "col" Collection “likes” Greater than or equal to 100 The data of , You can use the following command
db.col.find({
likes : {
$gte : 100}})
obtain "col" Collection “likes” Less than 150 The data of , You can use the following command :
db.col.find({
likes : {
$lt : 150}})
obtain "col" Collection “likes” Less than or equal to 150 The data of , You can use the following command :
db.col.find({
likes : {
$lte : 150}})
obtain "col" Collection “likes” Greater than 100, Less than 200 The data of , You can use the following command :
db.col.find({
likes : {
$lt :200, $gt : 100}})
MongoDB Limit and Skip The operator
Limit The operator ,Number Indicates the number of records read
db.COLLECTION_NAME.find().limit(NUMBER)
MongoDB skip() Method
Number Indicates the number of records to skip , The default from the 0 Start
db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
1.11、MongoDB $type The operator
MongoDB $type Operator table
type | Numbers | remarks |
---|---|---|
Double | 1 | |
Object | 2 | |
Array | 4 | |
Binary data | 5 | |
Undefined | 6 | obsolete |
Object id | 7 | |
Boolean | 8 | |
Date | 9 | |
Null | 10 | |
Regular Expression | 11 | |
JavaScript | 13 | |
Symbol | 14 | |
JavaScript (with scope) | 15 | |
32-bit integer | 16 | |
Timestamp | 17 | |
64-bit integer | 18 | |
Min key | 255 | Query with -1 |
Max key | 127 |
obtain “col” Collection title by String The data of , You can use the following command :
db.col.find({
"title" : {
$type : 2}})
1.12、MongoDB Sort
Use 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 .
This is to sort the set
db.COLLECTION_NAME.find().sort({
KEY:1})
1.13、MongoDB Indexes
An index is a special data structure , The index is stored in a collection of data that is easy to read through , An index is a structure that sorts the values of a column or columns in a database table . Indexing can improve query speed . If there is no index ,MongoDB When the data is read, each file in the collection must be scanned and those records that meet the query criteria must be selected .
demo: Inquire about col aggregate ,“title” For index fields ,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 .
db.col.ensureIndex({
"title":1})
Create indexes in the background
db.values.ensureIndex({
open: 1, close: 1}, {
background: true})
1.14、MongoDB 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(*).
Basic grammar such as :
db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
demo: Count the number of articles written by each author through the collection , Use aggregate() The calculation results are as follows :
db.mycol.aggregate([{
$group : {
_id : "$by_user", num_tutorial : {
$sum : 1}}}])
The above example is similar to sql sentence :select by_user, count(*) from mycol group by by_user
边栏推荐
- Solve the cache problem of reactnative using WebView
- 全志A40i/T3如何通过SPI转CAN
- The difference between tail -f, tail -f and tail
- RK3568开发板评测篇(二):开发环境搭建
- Rk3568 development board evaluation (II): development environment construction
- Initial order of pointer (basic)
- [AUTOSAR eight OS]
- [flutter] icons component (load the built-in icon of flutter | display the material design icon completely)
- Data analysis, thinking, law breaking and professional knowledge -- analysis method (I)
- 电话网络问题
猜你喜欢
Asynchronous, email and scheduled tasks
ROS2之ESP32简单速度消息测试(极限频率)
用Go+绘制爱心给心爱的她表白
Infrared thermography temperature detection system based on arm rk3568
[AUTOSAR II appl overview]
寻找标杆战友 | 百万级实时数据平台,终身免费使用
Embrace the safety concept of platform delivery
(C语言)数据的存储
Key detection and sinusoidal signal output developed by Arduino
数据分析思维分析犯法和业务知识——分析方法(一)
随机推荐
2022 list of manufacturers of Chinese 3D vision enterprises (guided positioning and sorting scenes)
The R language uses the ctree function in the party package to build conditional inference decision trees, uses the plot function to visualize the trained conditional inference decision tree, and the
MongoDB系列之MongoDB常用命令
Thank you for being together for these extraordinary two years!
Test shift right: Elk practice of online quality monitoring
JS inheritance and prototype chain
[AUTOSAR II appl overview]
世平信息首席科学家吕喆:构建以数据和人员为中心的安全能力
Solve the cache problem of reactnative using WebView
Trois tâches principales: asynchrone, courrier et timing
瑞萨RZ/G2L 处理器简介|框架图|功耗|原理图及硬件设计指南
R language ggplot2 visualization: use ggplot2 to display dataframe data that are all classified variables in the form of thermal diagram, and customize the legend color legend of factor
Meaning of Tencent cloud free SSL certificate extension file
鏈錶內指定區間反轉
[overview of AUTOSAR three RTE]
Web2.0 giants have deployed VC, and tiger Dao VC may become a shortcut to Web3
leetcode:871. 最低加油次数【以前pat做过 + 最大堆 +贪心】
[AUTOSAR I overview]
Tensorflow 2. Chapter 15 of X (keras) source code explanation: migration learning and fine tuning
Leetcode-1964: find the longest effective obstacle race route to each position