当前位置:网站首页>03 summary of various additions, updates and deletions of mongodb documents
03 summary of various additions, updates and deletions of mongodb documents
2022-06-28 04:05:00 【cui_ yonghua】
Catalog : The basic chapter ( Can solve the problem of 80 The problem of )
01 MongoDB Overview 、 Application scenarios 、 Download mode 、 Connection mode and development history, etc
02 MongoDB data type 、 Key concepts and shell Commonly used instructions
03 MongoDB Various additions to documents 、 to update 、 Delete operation summary
04 MongoDB Various query operations And summary of aggregation operations
05 MongoDB Summarize the various operations of the column
python3 operation MongoDB Various cases of
One . Inserted into the document
Be careful : stay MongoDB in , Inserting content directly will automatically create a collection !
1.1 Use insert() Method
Grammar format : db.COLLECTION_NAME.insert(document)
explain : If the inserted data primary key already exists , You'll throw it org.springframework.dao.DuplicateKeyException abnormal , Prompt for duplicate primary key , Do not save current data .
Case study : Such as directed set user_demo Insert a piece of data in :
db.user_demo.insert({
"name":"zhangsan", "age": 18})
# amount to sql Medium
insert into user_demo(name, age) values("zhangsan", 18);
1.2 Use save() Method ( Obsolete in the new version )
Grammar format : db.COLLECTION_NAME.save(document)
explain : If _id If the primary key exists, update the data , If it doesn't exist, insert data . The method is obsolete in the new version , have access to db.collection.insertOne() or db.collection.replaceOne() Instead of .
1.3 Use insertOne() Method (3.2 Version added )
Grammar format : db.collection.insertOne()
explain : Inserts a document data into the specified collection , Parameters can be specified :
writeConcern: Write strategy , The default is 1, That is, it is required to confirm the write operation ,0 Is not required .
Case study : Such as directed set user_demo Insert a piece of data in :
db.user_demo.insertOne({
"name":"zhangsan", "age": 18})
1.4 insertMany() Method (3.2 Version added )
Grammar format : db.collection.insertMany()
explain : Inserts multiple document data into the specified collection , Parameters can be specified :
writeConcern: Write strategy , The default is 1, That is, it is required to confirm the write operation ,0 Is not required ;
ordered: Specifies whether to write in order , Default true, Write in order .
Case study : Such as directed set user_demo Insert 2 Data :
db.user_demo.insertMany([{
"name":"zhangsan", "age": 18}, {
"name":"lisi", "age": 20}])
Two . Update the document
2.1 Use update() Method
Grammar format :
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
)
explain : Update documents in collection , Parameters can be specified :
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 .
Case study : Such as directed set user_demo In the name of zhangsan Of users age Update to 21:
db.user_demo.update({
'name':'zhangsan'},{
$set:{
'age': 21}})
# amount to sql Medium
update article set age = 21 where name > 'zhangsan';
2.2 Use save() Method
Grammar format :
db.collection.save(
<document>,
{
writeConcern: <document>
}
)
explain : save() Method to replace an existing document with an incoming document ,_id Update the primary key if it exists , Insert if it doesn't exist , Parameters can be specified :
document: Document data ;writeConcern: Optional , The level at which an exception is thrown .
Case study : Such as directed set user_demo replace _id by 56064f89ade2f21f36b03136 Document data
db.user_demo.save({
"_id" : ObjectId("56064f89ade2f21f36b03136"),
"name": "wangwu",
"age": 23})
# After the update, you can view the results
db.user_demo.find().pretty()
3.3 MongoDB 3.2 How to add new versions
Update one :db.collection.updateOne(), Reference resources :MongoDB Official website -updateOne operation
Update multiple :db.collection.updateMany(), Reference resources :MongoDB Official website -updateMany operation
Replace 1 strip :db.collection.replaceOne(), Reference resources :MongoDB Official website -replaceOne operation
3、 ... and . Delete the document
Be careful : Execute... Before deleting the document find() Command to determine if the conditions for execution are correct , This is a good habit .
3.1 Use remove() Method to delete the document
Grammar format : 2.6 After the version
db.collection.remove(
<query>,
{
justOne: <boolean>,
writeConcern: <document>
}
)
explain : Used to remove data from a collection , Parameter description :
query:( Optional ) Conditions for deleted documents .justOne: ( Optional ) If it is set to true or 1, Only one document is deleted , If this parameter is not set , Or use default values false, Deletes all documents that match the criteria .writeConcern:( Optional ) The level at which an exception is thrown .
Case study : For example, in the collection user_demo Remove the name from the middle zhangsan The data of :
db.user_demo.remove({
"name":"zhangsan"})
db.user_demo.find() # Found no named zhangsan The data of the
# amount to sql Medium
delete from user_demo where name = "zhangsan"
Be careful :remove() Method is out of date , Now the official recommendation is deleteOne() and deleteMany() Method .
3.2 Use deleteOne() Method to delete the document
If you delete user_demo Set below status be equal to D A document of :
db.inventory.deleteOne({ status: "D"})
3.3 Use deleteMany() Method to delete the document
If you delete user_demo All documents under the collection :db.user_demo.deleteMany({})
If you delete user_demo Set below status be equal to A All documents of :db.user_demo.deleteMany({status :"A"})
Four . bulk-write operation
MongoDB Batch operation supports the simultaneous execution of a batch of write operations , Write operations include : Inserted into the document 、 Update the document 、 Delete the document .
Official website reference : MongoDB Official website bulk-write operation
bulkWrite The following write operations can be combined freely for batch operations .
- insertOne - Insert a document
- updateOne - Update a document
- updateMany - Update a batch of documents
- replaceOne - Replace a document
- deleteOne - Delete a document
- deleteMany - Delete a batch of documents
Grammar format :
# operation - Represents the write operation configuration
# bulkWrite Receive an array of write operations .
db.collection.bulkWrite(
[ <operation 1>, <operation 2>, ... ],
)
mongo shell adopt db.collection.bulkWrite() Function to perform batch operations .
Comprehensive case :
db.inventory.bulkWrite(
[
// Insert a document
{
insertOne :
{
// Document content
"document" :
{
"_id" : 4, "char" : "Dithras", "class" : "barbarian", "lvl" : 4
}
}
},
{
insertOne :
{
"document" :
{
"_id" : 5, "char" : "Taeln", "class" : "fighter", "lvl" : 3
}
}
},
// Update a document ,updateMany Updating a batch of documents is similar to
{
updateOne :
{
// Update conditions
"filter" : {
"char" : "Eldon" },
// Update the content
"update" : {
$set : {
"status" : "Critical Injury" } }
}
},
// Delete a document ,deleteMany Deleting multiple documents is similar to
{
deleteOne :
// Delete the condition
{
"filter" : {
"char" : "Brisbane" } }
},
// Replace a document
{
replaceOne :
{
// Replacement conditions
"filter" : {
"char" : "Meldane" },
// replace content
"replacement" : {
"char" : "Tanys", "class" : "oracle", "lvl" : 4 }
}
}
]
);
attach : Official website crud operation : Official website crud operation
️ If it works , Thank you for clicking three times !!!️
边栏推荐
- Market competitiveness of robot programming education
- Arrangement of basic electrical knowledge (I)
- django. core. exceptions. ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3
- C语言十进制与BCD码的相互转换
- 猫狗队列的问题
- 开启创客教育造物学的领域
- Arrangement of basic electrical knowledge (II)
- 谈云原生,不得不谈的容器
- 等保2.0密码要求是什么?法律依据有哪些?
- Detailed explanation of iptables firewall rules and firewalld firewall rules
猜你喜欢

美创数据安全管理平台获信通院“数据安全产品能力验证计划”评测证书

音频 scipy 中 spectrogram 的运作机制

解析STEAM教育框架下未来教师研究能力

Several ways of sharing printers in LAN

Chapter 1 Introduction to bash

How to write a software test report? Here comes the third party performance report template

Pycharm setting pseudo sublime color scheme

电学基础知识整理(一)

django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3

Arrangement of basic electrical knowledge (II)
随机推荐
从零到一,教你搭建「以文搜图」搜索服务(一)
leetcode - 329. 矩阵中的最长递增路径
基于arm5718的Shell脚本参数传递的2种方法
美创入选“2022 CCIA中国网络安全竞争力50强”榜单
English语法_形容词/副词3级 - 比较级
电学基础知识整理(一)
Pycharm setting pseudo sublime color scheme
利用ELK 搭建日志分析系统(一)—— 组件介绍
Door level modeling - learning notes
【小程序实战系列】电商平台源码及功能实现
电学基础知识整理(二)
回溯—迷宫问题
How to apply for ASTM E108 flame retardant test for photovoltaic panels?
applicationContext.getBeansOfType 获取一个接口下所有实现类 执行方法或者获取实现类对象等 操作应用场景学习总结
【Linux】【Mysql】ERROR 1698 (28000): Access denied for user ‘root‘@‘localhost‘
leetcode:494. All methods of adding and subtracting operators to the array to get the specified value
窗帘做EN 1101易燃性测试过程是怎么样的?
gcd最大公约数
2021年终总结及2022年展望
Using elk to build a log analysis system (I) -- component introduction