Table of Contents
2.1 Syntax and function description
1.2 Operation Case
1.3 Combined with the $each modifier, batch insertion
1.4 The use of array modifiers $sort and $slice
2. $pop operator
3.2 Operation case
$pull operator " >3. $pull operator
3.1 Syntax and Function Description" >3.1 Syntax and Function Description
3.2.1 Remove the equal to specified value# in the array# The ## element
specified conditions
3.2.3 移除数组中内嵌子文档(即此时数组元素是子文档,每一个{}中的内容是一个数组元素)
3.2.4 如果数组类型的元素还内嵌一个数组(数组包数组),就要特别小心了。
4.$addToSet
4.1 语法及功能描述
4.2 操作案例
4.3 注意点
Home Database Mysql Tutorial Operations on array types in MongoDB (code example)

Operations on array types in MongoDB (code example)

Jan 30, 2019 am 10:26 AM
mongodb

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$pushAdd values ​​to an array$pushAllAdd an array to an array. (will be replaced by $rach)$addToSet$popRemove the first or last value from the array. $pullRemove values ​​matching the query criteria from the array. $pullAllRemove 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

$eachwith $push and $addToSet Used together to manipulate multiple values. $sliceUse with $push and $each to reduce the size of the updated array. $sortWork with $push, $each, and $slice to sort the subdocuments in the array.

1.$push operator

1.1 Syntax and function description

$push is mainly used to add elements to an array.

Syntax:

{ $push: { <field1>: <value1>, ... } }
Copy after login

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 } ] }
Copy after login

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}}})
Copy after login

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 } ] }
Copy after login

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 <span class="pre">$each. </span>

<span class="pre">For example, we add Xiaohong’s (_id =2) physics scores, chemistry scores, and biology scores to the document. The executed statement is as follows: </span>

db.studentscore.update({ _id: 2 },
    {
        $push: {
            score: {
                $each: [{ "physics": 100 }, { "chemistry": 90 }, { "biology": 99 }]
            }

        }
    }
)
Copy after login

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 } ] }
Copy after login

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 }   
      ]
      }
Copy after login

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
       }
     }
   }
)
Copy after login

The updated results are displayed as follows:

{
  "_id" : 5,
  "quizzes" : [
     { "wk" : 1, "score" : 10 },
     { "wk" : 2, "score" : 8 },
     { "wk" : 5, "score" : 8 }  ]}
Copy after login

$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: { <field>: <-1 | 1>, ... } }
Copy after login

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 ] }
Copy after login

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 } } )
Copy after login

After the update, the document is as follows

{ _id: 1, scores: [ 9, 10 ] }
Copy after login

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 } } )
Copy after login

The query results are as follows:

{ _id: 1, scores: [ 9 ] }
Copy after login

3. <span class="pre">$pull operator</span>

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: { <field1>: <value|condition>, <field2>: <value|condition>, ... } }
Copy after login

3.2 Operation case

3.2.1 Remove the equal to specified value# in the array# The ## element
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" ]}
Copy after login

The operation requirement is to add

"apples in the array field fruits "<span class="pre"></span> and "oranges" are removed, and "carrots" in the vegetables array field is also removed. The update statement is as follows: <span class="pre"></span>

db.stores.update(
    { },
    { $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } },
    { multi: true }
)
Copy after login

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" ]}
Copy after login

At this time, in the collection document, the array field of fruit There are no

apples or <span class="pre"></span>oranges, and there are no carrots in the vegetable array field. <span class="pre"></span>

3.2.2 Remove elements from the array that meet
specified conditions
If we have a collection of profiles, its document format is as follows:

{ _id: 1, votes: [ 3, 5, 6, 7, 7, 8 ] }
Copy after login

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 } } } )
Copy after login

The updated results are as follows:

{ _id: 1, votes: [  3,  5 ] }
Copy after login

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 }   ]}
Copy after login

需求是将 <span class="pre">score 为</span> <span class="pre">8</span> 并且 <span class="pre">item</span><span class="pre">"B"的元素移除</span>

db.survey.update(
  { },
  { $pull: { results: { score: 8 , item: "B" } } },
  { multi: true }
)
Copy after login

更新后的文档如下:

{
   "_id" : 1,
   "results" : [ { "item" : "A", "score" : 5 } ]}
{
  "_id" : 2,
  "results" : [
      { "item" : "C", "score" : 8, "comment" : "Strongly agree" },
      { "item" : "B", "score" : 4 }   ]}
Copy after login

3.2.4 如果数组类型的元素还内嵌一个数组(数组包数组),就要特别小心了。

此时就要用到 <span class="pre">$elemMatch操作符。</span>

例如 文档格式如下:

{
   _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 } ] }
   ]
}
Copy after login

需要将 results数组字段 移除,移除的条件是 results数组字段中的answers字段,符合 <span class="pre">q</span><span class="pre">2</span> and <span class="pre">a</span> 大于等于 <span class="pre">8。</span>

db.survey.update(
  { },
  { $pull: { results: { answers: { $elemMatch: { q: 2, a: { $gte: 8 } } } } } },
  { multi: true }
)
Copy after login

更新后的数据如下:

{
   "_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 } ] }
   ]
}
Copy after login

4.$addToSet

4.1 语法及功能描述

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

{ $addToSet: { <field1>: <value1>, ... } }
Copy after login

4.2 操作案例

假如有一个集合 <span class="pre">inventory</span> 格式如下

{ _id: 1, item: "polarizing_filter", tags: [ "electronics", "camera" ] }
Copy after login

我们希望向向字段 tags 数组 ,添加一个元素accessories,则更新语句如下:

db.inventory.update(
   { _id: 1 },
   { $addToSet: { tags: "accessories" } }
)
Copy after login

更新后的结果为

{ "_id" : 1, "item" : "polarizing_filter", "tags" : [ "electronics", "camera", "accessories" ] }
Copy after login

如果想批量的增加如果元素,我们可以结合 <span class="pre">$each 操作符一起使用。</span>

例如以下文档

{ _id: 2, item: "cable", tags: [ "electronics", "supplies" ] }
Copy after login

我们想在字段 tags 数组,添加元素 "camera", "electronics", "accessories",则更新语句如下:

db.inventory.update(
   { _id: 2 },
   { $addToSet: { tags: { $each: [ "camera", "electronics", "accessories" ] } } }
 )
Copy after login

更新后的结果如下:

{
  _id: 2,
  item: "cable",
  tags: [ "electronics", "supplies", "camera", "accessories" ]}
Copy after login

4.3 注意点

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

例如

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

执行的语句如下:

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

查询结构显示为

{ _id: 1, letters: [ "a", "b", [ "c", "d" ] ] }
Copy after login
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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1247
24
Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Apr 18, 2025 am 11:48 AM

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

How to configure MongoDB automatic expansion on Debian How to configure MongoDB automatic expansion on Debian Apr 02, 2025 am 07:36 AM

This article introduces how to configure MongoDB on Debian system to achieve automatic expansion. The main steps include setting up the MongoDB replica set and disk space monitoring. 1. MongoDB installation First, make sure that MongoDB is installed on the Debian system. Install using the following command: sudoaptupdatesudoaptinstall-ymongodb-org 2. Configuring MongoDB replica set MongoDB replica set ensures high availability and data redundancy, which is the basis for achieving automatic capacity expansion. Start MongoDB service: sudosystemctlstartmongodsudosys

How to ensure high availability of MongoDB on Debian How to ensure high availability of MongoDB on Debian Apr 02, 2025 am 07:21 AM

This article describes how to build a highly available MongoDB database on a Debian system. We will explore multiple ways to ensure data security and services continue to operate. Key strategy: ReplicaSet: ReplicaSet: Use replicasets to achieve data redundancy and automatic failover. When a master node fails, the replica set will automatically elect a new master node to ensure the continuous availability of the service. Data backup and recovery: Regularly use the mongodump command to backup the database and formulate effective recovery strategies to deal with the risk of data loss. Monitoring and Alarms: Deploy monitoring tools (such as Prometheus, Grafana) to monitor the running status of MongoDB in real time, and

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

What is the CentOS MongoDB backup strategy? What is the CentOS MongoDB backup strategy? Apr 14, 2025 pm 04:51 PM

Detailed explanation of MongoDB efficient backup strategy under CentOS system This article will introduce in detail the various strategies for implementing MongoDB backup on CentOS system to ensure data security and business continuity. We will cover manual backups, timed backups, automated script backups, and backup methods in Docker container environments, and provide best practices for backup file management. Manual backup: Use the mongodump command to perform manual full backup, for example: mongodump-hlocalhost:27017-u username-p password-d database name-o/backup directory This command will export the data and metadata of the specified database to the specified backup directory.

How to choose a database for GitLab on CentOS How to choose a database for GitLab on CentOS Apr 14, 2025 pm 04:48 PM

GitLab Database Deployment Guide on CentOS System Selecting the right database is a key step in successfully deploying GitLab. GitLab is compatible with a variety of databases, including MySQL, PostgreSQL, and MongoDB. This article will explain in detail how to select and configure these databases. Database selection recommendation MySQL: a widely used relational database management system (RDBMS), with stable performance and suitable for most GitLab deployment scenarios. PostgreSQL: Powerful open source RDBMS, supports complex queries and advanced features, suitable for handling large data sets. MongoDB: Popular NoSQL database, good at handling sea

How to encrypt data in Debian MongoDB How to encrypt data in Debian MongoDB Apr 12, 2025 pm 08:03 PM

Encrypting MongoDB database on a Debian system requires following the following steps: Step 1: Install MongoDB First, make sure your Debian system has MongoDB installed. If not, please refer to the official MongoDB document for installation: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-debian/Step 2: Generate the encryption key file Create a file containing the encryption key and set the correct permissions: ddif=/dev/urandomof=/etc/mongodb-keyfilebs=512

How to set up users in mongodb How to set up users in mongodb Apr 12, 2025 am 08:51 AM

To set up a MongoDB user, follow these steps: 1. Connect to the server and create an administrator user. 2. Create a database to grant users access. 3. Use the createUser command to create a user and specify their role and database access rights. 4. Use the getUsers command to check the created user. 5. Optionally set other permissions or grant users permissions to a specific collection.

See all articles