当前位置:网站首页>Mongodb array operation
Mongodb array operation
2022-06-13 00:36:00 【A small snail in a big city】
1. Add an element to the end of the array
push Is that , If the specified key already exists , It adds an element to the end of an existing array , If not, a new array will be created
db.user.update({
“_id” : ObjectId(“4ffcb2ed65282ea95f7e3304”)},{
$push:{
“relationships”:{
“fname”:”xiong”,”lname”:”lan”}}})
"_id" : ObjectId("4ffcb2ed65282ea95f7e3304"),
"age" : 23,
"favorite" : {
"1" : "reading",
"2" : "swimming",
"3" : "listening music"
},
"fname" : "jeff",
"height" : 166,
"lname" : "jiang",
"relationships" : [
{
"fname" : "deng",
"lname" : "pan"
},
{
"fname" : "qiang",
"lname" : "he"
},
{
"fname" : "dongren",
"lname" : "zeng"
},
{
"fname" : "xiong",
"lname" : "lan"
}
]
2. Delete an element at the end of the array
Do... On the array “ reduce ” operation , Can achieve pair array “ reduce ” There are two modifiers for the purpose ,pop and pull
db.user.update({
“_id” : ObjectId(“4ffcb2ed65282ea95f7e3304”)},{
$pop:{
“relationships”:1}})
"_id" : ObjectId("4ffcb2ed65282ea95f7e3304"),
"age" : 23,
"favorite" : {
"1" : "reading",
"2" : "swimming",
"3" : "listening music"
},
"fname" : "jeff",
"height" : 166,
"lname" : "jiang",
"relationships" : [
{
"fname" : "deng",
"lname" : "pan"
},
{
"fname" : "qiang",
"lname" : "he"
},
{
"fname" : "dongren",
"lname" : "zeng"
},
]
3. Delete an element at the beginning of the array
What should I do to delete from the beginning of the array . It's simple , Put the above “1” Change to “-1”, It will reverse the operation
db.user.update({
“_id” : ObjectId(“4ffcb2ed65282ea95f7e3304”)},{
$pop:{
“relationships”:-1}})
"_id" : ObjectId("4ffcb2ed65282ea95f7e3304"),
"age" : 23,
"favorite" : {
"1" : "reading",
"2" : "swimming",
"3" : "listening music"
},
"fname" : "jeff",
"height" : 166,
"lname" : "jiang",
"relationships" : [
{
"fname" : "qiang",
"lname" : "he"
},
{
"fname" : "dongren",
"lname" : "zeng"
}
]
4. Delete an element from the middle of the array
Want to delete the middle of the array . At this time ,$pull Come in handy
pull You can delete the data in the middle of the array . Here's one more thing to note ,pull All matched data will be deleted
db.user.update({
“_id” : ObjectId(“4ffcb2ed65282ea95f7e3304”)},{
$pull:{
“relationships”:{
“fname”:”dongren”,”lname”:”zeng”}}})
"_id" : ObjectId("4ffcb2ed65282ea95f7e3304"),
"age" : 23,
"favorite" : {
"1" : "reading",
"2" : "swimming",
"3" : "listening music"
},
"fname" : "jeff",
"height" : 166,
"lname" : "jiang",
"relationships" : [
{
"fname" : "qiang",
"lname" : "he"
},
{
"fname" : "xiong",
"lname" : "lan"
}
]
5. Filter element
1. We insert the same data into the array , It can be inserted into the array normally . And in the actual production environment , We don't want to see such a result ,
that , Here are two more modifiers that you can use :ne and addToSet.$ne Mainly used to judge , If there is this value in array , Do not insert ; No, just insert it
db.user.update({
“relationships.fname”:{
ne:"xiong"}},{
set:{
“fname”:”xiong”,”lname”:”lan”}})
"_id" : ObjectId("4ffcb2ed65282ea95f7e3304"),
"age" : 23,
"favorite" : {
"1" : "reading",
"2" : "swimming",
"3" : "listening music"
},
"fname" : "jeff",
"height" : 166,
"lname" : "jiang",
"relationships" : [
{
"fname" : "qiang",
"lname" : "he"
},
{
"fname" : "xiong",
"lname" : "lan"
},
]
2.ddToSet Than ne Better to use , It can determine whether the data exists by itself , And it and each Use a combination of , You can also insert multiple data into an array at the same time , This is a ne It can't be done
db.user.update({
“_id” : ObjectId(“4ffcb2ed65282ea95f7e3304”)},{
addToSet:{
"relationships":{
each:[{
“fname”:”xiong”,”lname”:”lan”},
{
“fname”:”dongren”,”lname”:”zeng”}]}}})
"_id" : ObjectId("4ffcb2ed65282ea95f7e3304"),
"age" : 23,
"favorite" : {
"1" : "reading",
"2" : "swimming",
"3" : "listening music"
},
"fname" : "jeff",
"height" : 166,
"lname" : "jiang",
"relationships" : [
{
"fname" : "qiang",
"lname" : "he"
},
{
"fname" : "xiong",
"lname" : "lan"
},
{
"fname" : "xiong",
"lname" : "lan"
},
{
"fname" : "dongren",
"lname" : "zeng"
}
]
In a modification statement , We want to insert... At the same time {“fname”:”xiong”,”lname”:”lan”},
{“fname”:”dongren”,”lname”:”zeng”} Two figures , But in the original array ,
{“fname”:”xiong”,”lname”:”lan”} This data already exists , So it just inserted the back one . We have achieved what we want . therefore , I personally prefer to use $addToSet
6. Operate on some of them
Sometimes an array has multiple values , And we just want to operate on some of them . If we copy down the whole document , That's too much trouble and stupid . Fortunately mongodb It provides us with two simple methods : By position or operator “$”. Let's take a look at how these two methods are used . The first is to operate through the array position . Arrays are all based on 0 At the beginning , You can use subscripts directly as keys to select elements . for example , We want to add the age key value pair to the first data of the array , We can do this :
db.user.update({
“_id” : ObjectId(“4ffcb2ed65282ea95f7e3304”)},{
$set:{
“relationships.0.age”:22}})
"_id" : ObjectId("4ffcb2ed65282ea95f7e3304"),
"age" : 23,
"favorite" : {
"1" : "reading",
"2" : "swimming",
"3" : "listening music"
},
"fname" : "jeff",
"height" : 166,
"lname" : "jiang",
"relationships" : [
{
"age" : 22,
"fname" : "qiang",
"lname" : "he"
},
{
"fname" : "deng",
"lname" : "pan"
},
{
"fname" : "xiong",
"lname" : "lan"
}
]
But in many cases , Without querying the document in advance, we don't know to modify the subscript of the elements of the array . Then the positioning operator “$” It's easy to use . It is used to locate the matching elements of the query document , And update . Let's see how it works :
db.user.update({
“relationships.fname”:”xiong”},{
set:{
"relationships..age”:22}})
"_id" : ObjectId("4ffcb2ed65282ea95f7e3304"),
"age" : 23,
"favorite" : {
"1" : "reading",
"2" : "swimming",
"3" : "listening music"
},
"fname" : "jeff",
"height" : 166,
"lname" : "jiang",
"relationships" : [
{
"age" : 22,
"fname" : "qiang",
"lname" : "he"
},
{
"age" : 22,
"fname" : "deng",
"lname" : "pan"
},
{
"age" : 22,
"fname" : "xiong",
"lname" : "lan"
}
]
7 mongodb in $ The role of
Definition
Locator $ To determine the position of an element to be updated in the array , Instead of specifying the position of the element in the array .
usage
1. Update the values in the array
1) Grammar format
{
"<array>.$": value}
2) Example
Create set students There are the following documents :
db.students.insert([
{
"_id" : 1, "grades" : [ 85, 80, 80 ] },
{
"_id" : 2, "grades" : [ 88, 90, 92 ] },
{
"_id" : 3, "grades" : [ 85, 100, 90 ] }
])
take grades The first value in the array is 80 Updated to 82, If you don't know the exact location of the first value , You can write like this :
db.students.updateOne(
{
_id: 1, grades: 80 },
{
$set: {
"grades.$" : 82 } }
)
Locator $ Like a placeholder , Match the first value that matches the query criteria .
2. Update the document in the array
Locators make it easy to update arrays that contain embedded documents . To get the field attribute value embedded in the document , Use the dot symbol after . Such as the following syntax format description
1) Grammar format
db.collection.update(
{
<query selector> },
{
<update operator>: {
"array.$.field" : value } }
)
2) give an example
hypothesis students Collection grades The array contains the following embedded documents :
{
_id: 4,
grades: [
{
grade: 80, mean: 75, std: 8 },
{
grade: 85, mean: 90, std: 5 },
{
grade: 85, mean: 85, std: 8 }
]
}
Use $ Locator to update grades Fields in the document in the array std Value , The updated document is the first match grade The value is 85 Documents . as follows :
db.students.updateOne(
{
_id: 4, "grades.grade": 85 },
{
$set: {
"grades.$.std" : 6 } }
)
The updated result is :
{
"_id" : 4,
"grades" : [
{
"grade" : 80, "mean" : 75, "std" : 8 },
{
"grade" : 85, "mean" : 90, "std" : 6 },
{
"grade" : 85, "mean" : 85, "std" : 8 }
]
}
边栏推荐
- BUUCTF之BabySQL[极客大挑战 2019]
- JPA execution failed in scheduled task -executing an update/delete query transactionrequiredexception
- 新增博客地址
- Tsinghua Bosch joint ml center, thbi lab:cheng Yang Ying | realize safety reinforcement learning through the value at risk of constraints
- Arduino controls tb6600 driver +42 stepper motor
- La différence entre philosophie et littérature
- Arduino control soil moisture sensor
- Five mock technologies of go
- [colorful] Net dto mapping
- Mysql批量插入数据时如何解决重复问题?
猜你喜欢

Maya modeling VI

Using com0com/com2tcp to realize TCP to serial port (win10)

Tsinghua Bosch joint ml center, thbi lab:cheng Yang Ying | realize safety reinforcement learning through the value at risk of constraints

MySQL lpad() and rpad() concatenate string functions with specified length

1. Google grpc framework source code analysis Hello World

Arduino control tm1637 common positive four digit nixie tube

从ADK的WinPE自己手动构建自己的PE

ik分词器的安装
![[Error] invalid use of incomplete type 使用了未定义的类型](/img/8a/7cb5d270cfd8831ddc146687fe4499.png)
[Error] invalid use of incomplete type 使用了未定义的类型
![[C] Inverts the binary of a decimal number and outputs it](/img/40/dcbe0aac2d0599189697db1f0080b5.jpg)
[C] Inverts the binary of a decimal number and outputs it
随机推荐
2022 beautician (technician) certificate title and answer
MySQL query table field information
[vscode]todo tree a to-do plug-in
Also on STM32 using dma+ serial port to obtain variable length data
Apispace empty number detection API interface is free and easy to use
[MRCTF2020]Ez_ bypass --BUUCTF
In / out / inout details of MySQL stored procedures
MASA Auth - 从用户的角度看整体设计
磁盘分区方式对比(MBR与GPT)
硬(磁)盘(二)
[GXYCTF2019]禁止套娃--详解
Solution to the problem of closing the watchdog of STM32 in the sleep mode (stop/standby)
Installation of IK word breaker
JPA execution failed in scheduled task -executing an update/delete query transactionrequiredexception
The e-commerce employee changed the product price to 10% off after leaving the company, and has been detained
Kalix system - use of information collection gadgets
Win10 home vs pro vs enterprise vs enterprise LTSC
BUUCTF之BabyUpload[GXYCTF2019]
TypeError: wave. ensureState is not a function
A simple deadlock example