The content this article brings to you is about the operation of array types in MongoDB (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
In MongoDB's schema, we often store some data in array types, which is an implementation of our common nested schema design. This design and implementation of arrays is not available or uncommon in relational databases. Therefore, through this article, we will sort out the related operations of MongoDB arrays. Operations on arrays can be divided into two categories, one is array operators and the other is array operation modifiers.
Array Operator
##Operator | Implement function |
Locate the document to be updated based on the query selector | |
Add values to an array | |
Add an array to an array. (will be replaced by $rach) | |
Add the value to the array, and it will not be processed if it is repeated | |
Remove the first or last value from the array. | |
Remove values matching the query criteria from the array. | |
Remove multiple values from an array. |
Array operation modifier
1.$push operator
$push is mainly used to add elements to an array.
Syntax:
{ $push: {: , ... } }
By default, it adds a single element to the end of the array.
Suppose we have a collection of student scores, studentscore, and its document format is as follows:
{ "_id" : 1, "name" : "xiaoming", "score" : [ { "math" : 99, "english" : 89 } ] } { "_id" : 2, "name" : "xiaohong", "score" : [ { "math" : 98, "english" : 96 } ] }
where The requirement is to update the document record with _id 1, add physics grades to the field of the score array, and modify the code to
db.studentscore.update({_id:1},{$push: {score:{"physics":100}}})
After modification , the result query is as follows:
{ "_id" : 1, "name" : "xiaoming", "score" : [ { "math" : 99, "english" : 89 }, { "physics" : 100 } ] } { "_id" : 2, "name" : "xiaohong", "score" : [ { "math" : 98, "english" : 96 } ] }
If multiple values are added to the array at one time, Can be used in conjunction with the array modifier$each.
For example, we add Xiaohong’s (_id =2) physics scores, chemistry scores, and biology scores to the document. The executed statement is as follows:
db.studentscore.update({ _id: 2 }, { $push: { score: { $each: [{ "physics": 100 }, { "chemistry": 90 }, { "biology": 99 }] } } } )
The query result is as follows:
{ "_id" : 1, "name" : "xiaoming", "score" : [ { "math" : 99, "english" : 89 }, { "physics" : 100 } ] } { "_id" : 2, "name" : "xiaohong", "score" : [ { "math" : 98, "english" : 96 }, { "physics" : 100 }, { "chemistry" : 90 }, { "biology" : 99 } ] }
We talked about the $each array operation modifier earlier, so let’s give another example to explain the remaining two modifiers together. ($sort and $slice)
For example, we have the following documentation:
{ "_id" : 5, "quizzes" : [ { "wk": 1, "score" : 10 }, { "wk": 2, "score" : 8 }, { "wk": 3, "score" : 5 }, { "wk": 4, "score" : 6 } ] }
Now we have a requirement, which is to first Add three records to the quizzes array field of the document. Then, we sort by score and select the first three elements in the array.
db.students.update( { _id: 5 }, { $push: { quizzes: { $each: [ { wk: 5, score: 8 }, { wk: 6, score: 7 }, { wk: 7, score: 6 } ], $sort: { score: -1 }, $slice: 3 } } } )
The updated results are displayed as follows:
{ "_id" : 5, "quizzes" : [ { "wk" : 1, "score" : 10 }, { "wk" : 2, "score" : 8 }, { "wk" : 5, "score" : 8 } ]}
$slice operation modifier It was added in MongoDB 2.4 to facilitate the management of frequently updated arrays. This operator is useful when adding values to an array but don't want the array to be too large. It must be used with the $push and $each operators, allowing it to be used to shorten the size of the array and delete old values.
Much like the $slice operation modifier, MongoDB 2.4 adds a new $sort operation modifier to help update arrays. When using $push and $slice, it is sometimes necessary to sort and then delete them.
The $pop operator can delete the first or best element from the array.
{ $pop: {: <-1 | 1>, ... } }
The parameter is -1, which means the first element in the array is to be deleted; the parameter is 1, which means the last element in the array is to be deleted.
For example, there are the following documents in the collection students:
{ _id: 1, scores: [ 8, 9, 10 ] }
Our need is to put the array into The first element (score 8) is removed, and the SQL statement is as follows:
db.students.update( { _id: 1 }, { $pop: { scores: -1 } } )
After the update, the document is as follows
{ _id: 1, scores: [ 9, 10 ] }
Continue to demonstrate, if we need to further remove the last element of the array (score is 10) on the existing basis, the updated SQL is as follows:
db.students.update( { _id: 1 }, { $pop: { scores: 1 } } )
The query results are as follows:
{ _id: 1, scores: [ 9 ] }
$pull operator
$pull is the complex form of $pop. Using $pull, you can specify exactly which elements to delete by value.
Syntax format
{ $pull: {: , : , ... } }
"apples in the array field fruits " and
"oranges" are removed, and "carrots" in the vegetables array field is also removed. The update statement is as follows:
apples or
oranges, and there are no carrots in the vegetable array field.
假设我们有一个关于 调查的集合 survey,其数据如下:
{ _id: 1, results: [ { item: "A", score: 5 }, { item: "B", score: 8, comment: "Strongly agree" } ]} { _id: 2, results: [ { item: "C", score: 8, comment: "Strongly agree" }, { item: "B", score: 4 } ]}
需求是将score 为
8
并且item
为"B"的元素移除
db.survey.update( { }, { $pull: { results: { score: 8 , item: "B" } } }, { multi: true } )
更新后的文档如下:
{ "_id" : 1, "results" : [ { "item" : "A", "score" : 5 } ]} { "_id" : 2, "results" : [ { "item" : "C", "score" : 8, "comment" : "Strongly agree" }, { "item" : "B", "score" : 4 } ]}
此时就要用到$elemMatch操作符。
例如 文档格式如下:
{ _id: 1, results: [ { item: "A", score: 5, answers: [ { q: 1, a: 4 }, { q: 2, a: 6 } ] }, { item: "B", score: 8, answers: [ { q: 1, a: 8 }, { q: 2, a: 9 } ] } ] } { _id: 2, results: [ { item: "C", score: 8, answers: [ { q: 1, a: 8 }, { q: 2, a: 7 } ] }, { item: "B", score: 4, answers: [ { q: 1, a: 0 }, { q: 2, a: 8 } ] } ] }
需要将 results数组字段 移除,移除的条件是 results数组字段中的answers字段,符合q
为2
anda
大于等于8。
db.survey.update( { }, { $pull: { results: { answers: { $elemMatch: { q: 2, a: { $gte: 8 } } } } } }, { multi: true } )
更新后的数据如下:
{ "_id" : 1, "results" : [ { "item" : "A", "score" : 5, "answers" : [ { "q" : 1, "a" : 4 }, { "q" : 2, "a" : 6 } ] } ] } { "_id" : 2, "results" : [ { "item" : "C", "score" : 8, "answers" : [ { "q" : 1, "a" : 8 }, { "q" : 2, "a" : 7 } ] } ] }
使用$addToSet也会往数组后面添加值,但是它比较特殊:它只会添加数组里不存在的值。
{ $addToSet: {: , ... } }
假如有一个集合inventory
格式如下
{ _id: 1, item: "polarizing_filter", tags: [ "electronics", "camera" ] }
我们希望向向字段tags 数组 ,添加一个元素accessories,则更新语句如下:
db.inventory.update( { _id: 1 }, { $addToSet: { tags: "accessories" } } )
更新后的结果为
{ "_id" : 1, "item" : "polarizing_filter", "tags" : [ "electronics", "camera", "accessories" ] }
如果想批量的增加如果元素,我们可以结合$each 操作符一起使用。
例如以下文档
{ _id: 2, item: "cable", tags: [ "electronics", "supplies" ] }
我们想在字段tags 数组,添加元素"camera","electronics","accessories",则更新语句如下:
db.inventory.update( { _id: 2 }, { $addToSet: { tags: { $each: [ "camera", "electronics", "accessories" ] } } } )
更新后的结果如下:
{ _id: 2, item: "cable", tags: [ "electronics", "supplies", "camera", "accessories" ]}
需要注意是,如果添加的元素是数组格式,则会将新添加的元素保留为数组(将会出现数组嵌套数组)
例如
{ _id: 1, letters: ["a", "b"] }
执行的语句如下:
db.test.update( { _id: 1 }, { $addToSet: {letters: [ "c", "d" ] } } )
查询结构显示为
{ _id: 1, letters: [ "a", "b", [ "c", "d" ] ] }
Modifier | Implement functions |
with $push and $addToSet Used together to manipulate multiple values. | |
Use with $push and $each to reduce the size of the updated array. | |
Work with $push, $each, and $slice to sort the subdocuments in the array. |
The above is the detailed content of Operations on array types in MongoDB (code example). For more information, please follow other related articles on the PHP Chinese website!