当前位置:网站首页>How mongodb inserts, deletes and updates documents
How mongodb inserts, deletes and updates documents
2022-07-29 05:18:00 【Yisu cloud】
MongoDB What's wrong Document Insert 、 Delete and update
This article mainly introduces MongoDB What's wrong Document Insert 、 Delete and update relevant knowledge , The content is detailed and easy to understand , The operation is simple and fast , It has certain reference value , I believe that after reading this article MongoDB What's wrong Document Insert 、 Deleting and updating articles will be beneficial , Let's have a look .
One .Document Insert data into
1. Inserted into the document
db.[ Document name ].insert({BSON data })2. Batch insert documents
shell Batch insertion is not supported , Want to complete the batch insert operation , have access to shell Of for loop , Or the batch operation method in other high-level languages
example : Use for Circular insert 10 A student , Among the students

I'm using 2.6 Version of , It is found that batch insert operation has been supported .
3.Save operation
save Operation and insert The difference in operation is ,save In case of _id When the same data is inserted , Will cover the original , and insert It will give you an error
Example :
use insert To insert a _id Same data

Two .Document Data deletion
1. Delete all data in the list
db.[ Document name ].remove({})The collection itself and index will not be deleted
Example : Delete all data in the list

2. Delete... According to conditions
example : Delete _id by 10 The record of

3、 ... and .Document Data update
1. Direct coverage update
db.[ Document name ].update({ Inquire device },{ Modifier }){ Inquire device } It's equivalent to the condition
{ Modifier } That's what you want to replace directly BSON data
example : to update _id by 9, The student , hold Name become age

Be careful : When the primary key conflicts, an error will be reported and the update operation will be stopped
example : I use _id by 8 The data of , Replace _id by 9 The record of , because _id by 8 The data already exists , Two primary keys are not allowed to be _id:8
The record of , So there's an error .

2. use insertOrUpdate To update
db.[ Document name ].update({ Inquire device },{ Modifier },true)The next third parameter is true, It means when the record doesn't exist , Just insert a record , Update if it exists
example : Update one _id by 10 The data of , Insert without , Update if you have

3. Batch update operation
db.[ Document name ].update({ Inquire device },{ Modifier },false, true)※ By default, the first data will be modified by default when the query finds multiple data
First modify the data as follows :
Give Way _id by 9 and 10 The data of , There's the same thing

Insert one more _id=11,age=20 The data of

The fourth parameter is updated without writing :
as follows : Only the first age=20 The data of

The fourth parameter is added and is true When , Our expectation is 10 and 11 Can be fixed
But when I try to update , Wrong report , The prompt says that batch update can only be done when $ Use when operating

Fixed insert statement
Note here $set There's going to be ":", And it and the modifiers behind it will be {} wrap up , Because I used it for the first time mongoDB, So it's always wrong .

4. Use the modifier to complete the local update operation
$set It is used to specify a key value pair , If there is a key, modify it. If there is no key, add it
{$set:{field:value}}_id by 10 The data of , No, Name attribute , Added , Yes age key , It was modified

$inc
1. For number types
2. It can add and subtract the number type value corresponding to the key
{$inc:{field:value}}to age=30 The data of 2 year , Since batch update parameters are not used , So the first one was amended by default

$unset Delete specified key
{$unset:{field:1}}In the example, I deleted age=30 Data. age attribute , But one thing I don't understand ,unset Behind the field:1 What is it? , So I checked , It doesn't matter what's behind it ,unset Just look at the key, not value, So I made a second example

$push
1. If the specified key is an array increment, append a new value
2. If the specified key is not an array, the current operation is interrupted , Report errors
3. If the specified key does not exist, create a key value pair of array type
{$push:{field:value}}
$pushAll
Same as above , Is the operation of batch adding array data
{$pushAll:{field:array}}1. The first operation doesn't work $pushAll, So the ["C#","JAVA"] Treated as an array item
2. The second operation uses $pushAll, So it's treated as two items .

$addToSet
Add items to the array , There is no need to add , Add... If it doesn't exist (push Add it whether it exists or not )
{$addToSet:{field:value}}1. First use push Insert , I found that after the update, there are two “C#”
2. Reuse addToSet to update , Found no additional items

$pop
Removes a value from the specified array 1 Delete the last value ,-1 Delete the first value
{$pop:{field:value}}1. Delete data from the last index position , hinder value use "1"
2. Delete the data of the first position index ,value=-1

$pull
push Reverse operation , The delete key is the specified element in the item of the array
{$pull:{field:value}}
$pullAll
Batch delete the specified elements in the array
{$pullAll:{field:array}}
$ Array locators , If the array has multiple values, we only want to operate on some of them, we need to use locators ($)
{$push:{field:value}}1. The first example is to add two elements to the array just cleared
2. I want to {“SubID”:1,"SubName":"MangoDB"} Add... To this object "Teacher":"Lucy"


5.$addToSet And $each Combined with the completion of batch array update
understand : First of all, from the example above, we know that ,addToSet This modifier , You can judge whether the project exists , Insert it when it doesn't exist .
Now I have a function , For example, I want to batch update data in an array with data , If it exists, it will not be updated . So just use addToSet You can't do it in batches , So we have to combine $each To achieve .
example :
1. Create a new file , And use pushAll Modifier to add data :

2. I want to batch insert "C#","PHP","JavaScript","JAVA", There should be no repetition of the requirements
If I use it right now pushAll To update ,"C#" and "JAVA" There will be repetition
stay shell Enter the following command :

About “MongoDB What's wrong Document Insert 、 Delete and update ” That's all for this article , Thank you for reading ! I'm sure you're right “MongoDB What's wrong Document Insert 、 Delete and update ” Knowledge has a certain understanding , If you want to learn more , Welcome to the Yisu cloud industry information channel .
边栏推荐
- Jackson解析JSON详细教程
- Original code, inverse code, complement code
- Learn the first program of database
- Getting started with solidity
- ARFoundation从零开始9-AR锚点(AR Anchor)
- What servers are needed to build mobile app
- P2181 diagonal
- [file download] easyexcel quick start
- How does word view document modification traces? How word views document modification traces
- ODOO开发教程之图表
猜你喜欢

Numpy Foundation

MySQL many to many relationship, grouping and splicing to query multiple data to one data

虚拟偶像的歌声原来是这样生成的!

传奇服务端如何添加地图

How does WPS take quick screenshots? WPS quick screenshot method
带你搞懂 Kubernetes 集群中几种常见的流量暴露方案

office2010每次打开都要配置进度怎么解决?

TCP三次握手四次挥手

【文件下载】Easyexcel快速上手

The method and detailed code of automatically pop-up and QQ group when players visit the website
随机推荐
Learn the first program of database
Vivo market API event reporting and docking
Pytorch learning notes
SM integration is as simple as before, and the steps are clear (detailed)
Word如何查看文档修改痕迹?Word查看文档修改痕迹的方法
[wechat applet -- solve the alignment problem of the last line of display:flex. (discontinuous arrangement will be divided into two sides)]
ARFoundation从零开始8-Geospatial API(地理空间)开发
SM整合原来这么简单,步骤清晰(详细)
NumPy基础
Google gtest事件机制
Raspberry pie 4B + Intel neural computing stick (stick2) +yolov5 feasibility study report
Architecture analysis of three-tier project and parameter name injection of construction method
Activity workflow table structure learning
Open source Huizhi creates the future | the openeuler sub forum of 2022 open atom global open source summit was successfully held
Arfoundation starts from scratch 3- create an arfoundation project
网安学习-内网安全1
Big silent event Google browser has no title
Use annotation test in idea
【微信小程序--解决display:flex最后一行对齐问题。(不连续排列会分到两边)】
浅谈AspectJ框架