search
HomeDatabaseMysql TutorialOperations on array types in MongoDB (code example)

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>, ... } }

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

        }
    }
)

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: { <field>: <-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. <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>, ... } }

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

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

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

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

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

需求是将 <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 }
)

更新后的文档如下:

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

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

需要将 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 }
)

更新后的数据如下:

{
   "_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: { <field1>: <value1>, ... } }

4.2 操作案例

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

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

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

例如以下文档

{ _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" ] ] }
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:博客园. If there is any infringement, please contact admin@php.cn delete
How to Grant Permissions to New MySQL UsersHow to Grant Permissions to New MySQL UsersMay 09, 2025 am 12:16 AM

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

How to Add Users in MySQL: A Step-by-Step GuideHow to Add Users in MySQL: A Step-by-Step GuideMay 09, 2025 am 12:14 AM

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

MySQL: Adding a new user with complex permissionsMySQL: Adding a new user with complex permissionsMay 09, 2025 am 12:09 AM

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

MySQL: String Data Types and CollationsMySQL: String Data Types and CollationsMay 09, 2025 am 12:08 AM

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

MySQL: What length should I use for VARCHARs?MySQL: What length should I use for VARCHARs?May 09, 2025 am 12:06 AM

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.

MySQL BLOB : are there any limits?MySQL BLOB : are there any limits?May 08, 2025 am 12:22 AM

MySQLBLOBshavelimits:TINYBLOB(255bytes),BLOB(65,535bytes),MEDIUMBLOB(16,777,215bytes),andLONGBLOB(4,294,967,295bytes).TouseBLOBseffectively:1)ConsiderperformanceimpactsandstorelargeBLOBsexternally;2)Managebackupsandreplicationcarefully;3)Usepathsinst

MySQL : What are the best tools to automate users creation?MySQL : What are the best tools to automate users creation?May 08, 2025 am 12:22 AM

The best tools and technologies for automating the creation of users in MySQL include: 1. MySQLWorkbench, suitable for small to medium-sized environments, easy to use but high resource consumption; 2. Ansible, suitable for multi-server environments, simple but steep learning curve; 3. Custom Python scripts, flexible but need to ensure script security; 4. Puppet and Chef, suitable for large-scale environments, complex but scalable. Scale, learning curve and integration needs should be considered when choosing.

MySQL: Can I search inside a blob?MySQL: Can I search inside a blob?May 08, 2025 am 12:20 AM

Yes,youcansearchinsideaBLOBinMySQLusingspecifictechniques.1)ConverttheBLOBtoaUTF-8stringwithCONVERTfunctionandsearchusingLIKE.2)ForcompressedBLOBs,useUNCOMPRESSbeforeconversion.3)Considerperformanceimpactsanddataencoding.4)Forcomplexdata,externalproc

See all articles

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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools