当前位置:网站首页>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 !!!️
边栏推荐
- English grammar_ Adjective / adverb Level 3 - Comparative
- 黑体辐射初探
- 【Linux】【Mysql】ERROR 1698 (28000): Access denied for user ‘root‘@‘localhost‘
- Notes to friendship chain
- 2021 year end summary and 2022 outlook
- Staggered and permutation combination formula
- 品达通用权限系统(Day 5~Day 6)
- What is the process of en 1101 flammability test for curtains?
- 窗帘做EN 1101易燃性测试过程是怎么样的?
- Pointer linked list
猜你喜欢

One article tells you what kubernetes is

Are the two flame retardant standards of European furniture en 597-1 and en 597-2 the same?

使用信号分析器

Understanding and learning of parental delegation mechanism

数字电路学习笔记(一)

黑体辐射初探

English grammar_ Adjective / adverb Level 3 - Comparative_ Useful Expressions

工业物联网将取代人工发展吗?

How to apply for ASTM E108 flame retardant test for photovoltaic panels?

MSC 307(88) (2010 FTPC Code)第2部分烟气和毒性测试
随机推荐
门级建模—学习笔记
揭开SSL的神秘面纱,了解如何用SSL保护数据
KVM常用命令详解
Pycharm setting pseudo sublime color scheme
MSC 307(88) (2010 FTPC Code) Part 9床上用品试验
多项目设计开发·类库项目引入入门
05 MongoDB对列的各种操作总结
Talking about cloud primitiveness, we have to talk about containers
基于正点原子stm32的mini板的TFTLCD显示实验
Web APIs DOM event foundation dark horse programmer
gcd最大公约数
Adder - Notes
错排兼排列组合公式
解析教育机器人的综合应用能力
PyCharm设置仿sublime配色方案
【MySQL】多表连接查询
Understanding and learning of parental delegation mechanism
Building log analysis system with elk (II) -- deployment and installation
2021 year end summary and 2022 outlook
如何修改SE38编辑器主题