Home Database Mysql Tutorial MongoDB入门篇--增删改查

MongoDB入门篇--增删改查

Jun 07, 2016 pm 04:12 PM
mongodb getting Started start up success

mongodb成功启动,接下来就该进行一系列操作了。我们再开一个cmd,输入【mongo】命令打开shell即mongodb的客户端,默认连接的是test数据库,我这里设置集合(表)为student。图一: 1. 添加insert 语法:db.集合.insert({Col1:列值1,Col2:列值2,,Coln:列值n}

mongodb成功启动,接下来就该进行一系列操作了。我们再开一个cmd,输入【mongo】命令打开shell即mongodb的客户端,默认连接的是“test”数据库,我这里设置集合(表)为student。图一:

\


1. 添加insert


语法:db.集合.insert({“Col1”:”列值1”,”Col2”:”列值2”,…,”Coln”:”列值n”})


2. 查找find


2.1全部查询


语法:db.集合.find()


2.2条件查询


语法:db.集合.find({“Col1”:”列值1”,”Col2”:”列值2”,…,”Coln”:”列值n”})


操作示例:添加+查找

\

注意:“_id"这个字段是数据库默认给我们加的GUID,目的是保证数据的唯一性。


3.修改


3.1全部修改update


语法:db.集合.update({“Col”:”列值”},{”Col2”:”列值2”,…,”Coln”:”列值n”})


注意:


第一个参数{…}为“查找的条件”,第二个参数{…}为“要更新的值”;
Update()为全部修改,第二个参数中需要包含全部的”字段”,否则更新后会造数据的丢失,具体影响请见下图示例。

操作示例:全部修改+错误实例

\



3.2.局部修改


Mongodb中为局部修改提供了两个修改器: $inc 和 $set。


① $inc修改器
$inc即increase的缩写,自增$inc指定的值,如果“文档”中没有此key,则会创建key。

语法:db.集合.update({"col1":"列值1"},{$inc:{"col2":"列值2",...,"coln":"列值n"}}

② $ set修改器

直接将对应的数据替换为$set指定的值。

语法:db.集合.update({"col1":"列值1"},{$set:{"col2":"列值2",...,"coln":"列值n"}})

操作示例:局部修改+高级修改

\


3.3 upsert操作


Upsert=update+insert,智能判断更新或添加,所以我更愿意称之为高级修改。也就是说:如果查到了文档直接更新,否则在数据库里面新增一条。 将update的第三个参数设为true即可。操作示例见上图。


语法:db.集合.update({"Col":"列值"},{$inc:{"Col2":"列值2",…,"Coln":"列值n"}},true)


3.4批量修改


在前面几个的基础上进行改进,不在多做解释。
语法:db.集合.update({"Col":"列值"},{$inc:{"Col2":"列值2",…,"Coln":"列值n"}},true,true)

操作示例:批量修改

\


4.删除remove


语法:db.集合.remove()
db.集合.remove({"Col":"列值"},{"Col2":"列值2",…,"Coln":"列值n"})

操作示例:删除

\


(5~6为高级操作,不做详细介绍)


5.分组查询group

操作示例:分组查找

\


6.除重distinct
7.统计count

操作示例:除重+统计

\

以上是我操作后的实例分享,再次操作一遍感觉收获的更多。还记得刚开始动手操作的时候,关于修改部分只接触了全部修改,当时那时候还以为跟其他数据库操作一样修改就是一个update()方法,所以实践的时候就直接进行了部分修改,后果就像图中显示的一样造成了数据丢失。当时还在想“不会吧,难道只修改一两个字段还要把所有的都写上吗?这也太麻烦了吧。。。”,后来跟旁边的大神周响师哥讨论他告诉我mongodb修改有两种方法也就是上文提到的mongodb专门封装的部分修改的方法。当时貌似当时走了弯路,不过现在想想真的是弯路吗?

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)

Why didn't I know when I was learning line generation: There is an equivalence relationship between matrices and graphs? Why didn't I know when I was learning line generation: There is an equivalence relationship between matrices and graphs? Aug 19, 2024 pm 04:52 PM

The matrix is ​​difficult to understand, but it may be different if you look at it from another perspective. When learning mathematics, we are often frustrated by the difficulty and abstractness of the knowledge we learn; but sometimes, just by changing the perspective, we can find a simple and intuitive solution to the problem. For example, when we were learning the formula for the sum of squares (a+b)² when we were children, we may not understand why it is equal to a²+2ab+b². We only knew that it was written like this in the book and the teacher asked us to remember it like this; until one day we saw I saw this animated picture: It suddenly dawned on me that we can understand it from a geometric perspective! Now, this sense of enlightenment occurs again: a non-negative matrix can be equivalently converted into the corresponding directed graph! As shown in the figure below, the 3×3 matrix on the left can actually be

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

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

Major update of Pi Coin: Pi Bank is coming! Major update of Pi Coin: Pi Bank is coming! Mar 03, 2025 pm 06:18 PM

PiNetwork is about to launch PiBank, a revolutionary mobile banking platform! PiNetwork today released a major update on Elmahrosa (Face) PIMISRBank, referred to as PiBank, which perfectly integrates traditional banking services with PiNetwork cryptocurrency functions to realize the atomic exchange of fiat currencies and cryptocurrencies (supports the swap between fiat currencies such as the US dollar, euro, and Indonesian rupiah with cryptocurrencies such as PiCoin, USDT, and USDC). What is the charm of PiBank? Let's find out! PiBank's main functions: One-stop management of bank accounts and cryptocurrency assets. Support real-time transactions and adopt biospecies

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

See all articles