Home Database Mysql Tutorial MongoDB数组修改器更新数据

MongoDB数组修改器更新数据

Jun 07, 2016 pm 02:58 PM
mongodb modifier number data array renew

MongoDB数组修改器更新数据 这里,我们将了解一下数组修改器。数组,是我们经常看到和使用到的且非常有用的数据结构:它不仅可以通过索进行引用,还可以作为集合来使用。数组修改器,顾名思义,它是用来修改数组的,而不能用来修改整数或者字符串。数组修改

MongoDB数组修改器更新数据

 

   这里,我们将了解一下数组修改器。数组,是我们经常看到和使用到的且非常有用的数据结构:它不仅可以通过索进行引用,还可以作为集合来使用。数组修改器,顾名思义,它是用来修改数组的,而不能用来修改整数或者字符串。数组修改器不多,就那么几个,但熟练掌握它后,将给我们带来非常方便的操作。下面,我们来了解一下:

> db.user.findOne()

{

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

        }

    ]

}

以上是我的还在完善中的个人信息文档。假设最近我又交了一个好朋友,我想把他加到我的人际关系“relationships”数组中。这时,$push修改器就派上用场了。$push的作用就是,如果指定的键已经存在,它会向已有的数组末尾加入一个元素,要是没有就会创建一个新的数组。下面我们把新朋友加进去。

> db.user.update({"_id" : ObjectId("4ffcb2ed65282ea95f7e3304")},{$push:{"relationships":{"fname":"xiong","lname":"lan"}}})

> db.user.findOne()

{

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

        }

    ]

}

有加就有减,那么怎么对数组进行“减”操作呢。能达到对数组“减”目的的修改器有两个,$pop和$pull。$pop和$pull又有区别,我们来分别实验。首先是$pop

> db.user.update({"_id" : ObjectId("4ffcb2ed65282ea95f7e3304")},{$pop:{"relationships":1}})

> db.user.findOne()

{

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

        }

    ]

}

从上面可以看出,它把我们刚加进去的朋友又删除了,也就是说它从数组的最后删除。那么,如果我们想从数组的开头删除该怎么办呢。很简单,把上面的“1”改成“-1”,它将逆向操作。下面看一下:

> db.user.update({"_id" : ObjectId("4ffcb2ed65282ea95f7e3304")},{$pop:{"relationships":-1}})

> db.user.findOne()

{

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

        }

    ]

}

从结果可以看出,它达到了我们预期的目的。那么如果我们想删除数组中间的呢。这时,$pull派上用场。首先,我们先将新朋友加进去,这里我不再演示。但我们可以想到“dongren”这个人是在数组的中间。现在我们要将他删除:

> db.user.update({"_id" : ObjectId("4ffcb2ed65282ea95f7e3304")},{$pull:{"relationships":{"fname":"dongren","lname":"zeng"}}})

> db.user.findOne()

{

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

        }

    ]

}

从上面可以看出,$pull可以将数组中间的数据删除。这里还有一点要注意,$pull会将所有匹配到的数据都删除,这里我就不做实验了。下面,我们再来看看$push还有什么特点,我们再往数组里插入一相同的数据,看看会如何:

> db.user.update({"_id" : ObjectId("4ffcb2ed65282ea95f7e3304")},{$push:{"relationships":{"fname":"xiong","lname":"lan"}}})

> db.user.findOne()

{

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

        }

    ]

}

结果表明,它是能正常插入到数组的。而在实际生产环境中,我们都不想看到这样的结果,那么,这里又出现了两个可以用的修改器:$ne和$addToSet。$ne主要拿来判断,若数组里面有这个值,则不插入;没有才插入。

> db.user.update({"relationships.fname":{$ne:"xiong"}},{$set:{"fname":"xiong","lname":"lan"}})

> db.user.findOne()

{

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

        }

    ]

}

由结果可以看出,由于该数据在数组中已经存在,所以不再插入。其实,$addToSet比$ne更好用,它可以自己判断数据是否存在,而且它和$each结合使用,还能同时在数组中插入多个数据,这是$ne没办法办到的,下面我们来看一下$addToSet的用法,这里顺便结合了$each的使用:

> db.user.update({"_id" : ObjectId("4ffcb2ed65282ea95f7e3304")},

{$addToSet:{"relationships":{$each:[{"fname":"xiong","lname":"lan"},

{"fname":"dongren","lname":"zeng"}]}}})

> db.user.findOne()

{

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

        }

    ]

}

在修改语句中,我们想同时插入{"fname":"xiong","lname":"lan"},

{"fname":"dongren","lname":"zeng"}两个数据,但在原数组中,

{"fname":"xiong","lname":"lan"}这个数据已经存在,所以它只插入了后面那条。达到了我们想要的目的。所以,我个人更喜欢使用$addToSet。

    有时候数组有多个值,而我们只想对其中的一部分进行操作。如果我们把整个文档都抄下来,那太麻烦也太愚蠢了。好在mongodb给我们提供了两种简便方法:通过位置或者操作符“$”。下面我们来分别看看这两种方法怎么使用。首先是通过数组位置来操作。数组都是以0开头的,可以将下标直接作为键来选择元素。例如,我们想给数组的第一个数据加上年龄键值对,我们可以这么操作:

> db.user.update({"_id" : ObjectId("4ffcb2ed65282ea95f7e3304")},{$set:{"relationships.0.age":22}})

> db.user.findOne()

{

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

        }

    ]

}

可是很多情况下,不预先查询文档我们就不知道要修改数组的元素的下标。这时定位操作符“$”就很好用了。它就是用来定位查询文档已匹配的元素,并进行更新。我们来看看它怎么用:

> db.user.update({"relationships.fname":"xiong"},{$set:{"relationships.$.age":22}})

> db.user.findOne()

{

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

        }

    ]

}

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)

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

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:

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.

MongoDB and relational database: a comprehensive comparison MongoDB and relational database: a comprehensive comparison Apr 08, 2025 pm 06:30 PM

MongoDB and relational database: In-depth comparison This article will explore in-depth the differences between NoSQL database MongoDB and traditional relational databases (such as MySQL and SQLServer). Relational databases use table structures of rows and columns to organize data, while MongoDB uses flexible document-oriented models to better suit the needs of modern applications. Mainly differentiates data structures: Relational databases use predefined schema tables to store data, and relationships between tables are established through primary keys and foreign keys; MongoDB uses JSON-like BSON documents to store them in a collection, and each document structure can be independently changed to achieve pattern-free design. Architectural design: Relational databases need to pre-defined fixed schema; MongoDB supports

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 sort mongodb index How to sort mongodb index Apr 12, 2025 am 08:45 AM

Sorting index is a type of MongoDB index that allows sorting documents in a collection by specific fields. Creating a sort index allows you to quickly sort query results without additional sorting operations. Advantages include quick sorting, override queries, and on-demand sorting. The syntax is db.collection.createIndex({ field: <sort order> }), where <sort order> is 1 (ascending order) or -1 (descending order). You can also create multi-field sorting indexes that sort multiple fields.

See all articles