Home>Article>Database> Operations on array types in MongoDB (code example)

Operations on array types in MongoDB (code example)

不言
不言 forward
2019-01-30 10:26:33 3714browse

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

$ Locate the document to be updated based on the query selector $push Add values to an array $pushAll Add an array to an array. (will be replaced by $rach) $addToSet $pop Remove the first or last value from the array. $pull Remove values matching the query criteria from the array. $pullAll Remove multiple values from an array.
##Operator Implement function
Add the value to the array, and it will not be processed if it is repeated

Array operation modifier

1.$push operator

1.1 Syntax and function description

$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.

1.2 Operation Case

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 } ] }

1.3 Combined with the $each modifier, batch insertion

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 } ] }

1.4 The use of array modifiers $sort and $slice

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.

2. $pop operator

2.1 Syntax and function description

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.

2.2 Operation case

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 ] }

3.$pull operator

3.1 Syntax and Function Description

$pull is the complex form of $pop. Using $pull, you can specify exactly which elements to delete by value.

Syntax format

{ $pull: { : , : , ... } }

3.2 Operation case

3.2.1 Remove the equal tospecified value# in the array# The ## element

"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.

specified conditions

3.2.3 移除数组中内嵌子文档(即此时数组元素是子文档,每一个{}中的内容是一个数组元素)

假设我们有一个关于 调查的集合 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 } ]}

3.2.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字段,符合q2anda大于等于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 } ] } ] }

4.$addToSet

4.1 语法及功能描述

使用$addToSet也会往数组后面添加值,但是它比较特殊:它只会添加数组里不存在的值。

{ $addToSet: { : , ... } }

4.2 操作案例

假如有一个集合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" ]}

4.3 注意点

需要注意是,如果添加的元素是数组格式,则会将新添加的元素保留为数组(将会出现数组嵌套数组)

例如

{ _id: 1, letters: ["a", "b"] }

执行的语句如下:

db.test.update( { _id: 1 }, { $addToSet: {letters: [ "c", "d" ] } } )

查询结构显示为

{ _id: 1, letters: [ "a", "b", [ "c", "d" ] ] }
$each with $push and $addToSet Used together to manipulate multiple values. $slice Use with $push and $each to reduce the size of the updated array. $sort Work with $push, $each, and $slice to sort the subdocuments in the array. test document is as follows:
{ _id: 1, fruits: [ "apples", "pears", "oranges", "grapes", "bananas" ], vegetables: [ "carrots", "celery", "squash", "carrots" ]} { _id: 2, fruits: [ "plums", "kiwis", "oranges", "bananas", "apples" ], vegetables: [ "broccoli", "zucchini", "carrots", "onions" ]}
The operation requirement is to add
db.stores.update( { }, { $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } }, { multi: true } )
The updated results are as follows:
{ "_id" : 1, "fruits" : [ "pears", "grapes", "bananas" ], "vegetables" : [ "celery", "squash" ]} { "_id" : 2, "fruits" : [ "plums", "kiwis", "bananas" ], "vegetables" : [ "broccoli", "zucchini", "onions" ]}
At this time, in the collection document, the array field of fruit There are no3.2.2 Remove elements from the array that meetIf we have a collection of profiles, its document format is as follows:
{ _id: 1, votes: [ 3, 5, 6, 7, 7, 8 ] }
We want to remove elements with votes greater than or equal to 6. The statement is as follows:
db.profiles.update( { _id: 1 }, { $pull: { votes: { $gte: 6 } } } )
The updated results are as follows:
{ _id: 1, votes: [ 3, 5 ] }
Modifier Implement functions

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!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete