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)

AI in use | AI created a life vlog of a girl living alone, which received tens of thousands of likes in 3 days AI in use | AI created a life vlog of a girl living alone, which received tens of thousands of likes in 3 days Aug 07, 2024 pm 10:53 PM

Editor of the Machine Power Report: Yang Wen The wave of artificial intelligence represented by large models and AIGC has been quietly changing the way we live and work, but most people still don’t know how to use it. Therefore, we have launched the "AI in Use" column to introduce in detail how to use AI through intuitive, interesting and concise artificial intelligence use cases and stimulate everyone's thinking. We also welcome readers to submit innovative, hands-on use cases. Video link: https://mp.weixin.qq.com/s/2hX_i7li3RqdE4u016yGhQ Recently, the life vlog of a girl living alone became popular on Xiaohongshu. An illustration-style animation, coupled with a few healing words, can be easily picked up in just a few days.

Another Sora-level player is coming to hit the streets! We compared it with Sora and Keling. Another Sora-level player is coming to hit the streets! We compared it with Sora and Keling. Aug 02, 2024 am 10:19 AM

When Sora failed to come out, OpenAI's opponents used their weapons to destroy the streets. If Sora is not open for use, it will really be stolen! Today, San Francisco startup LumaAI played a trump card and launched a new generation of AI video generation model DreamMachine. Free and available to everyone. According to reports, the model can generate high-quality, realistic videos based on simple text descriptions, with effects comparable to Sora. As soon as the news came out, a large number of users crowded into the official website to try it out. Although officials claim that the model can generate 120-frame video in just two minutes, many users have been waiting for hours on the official website due to a surge in visits. BarkleyDai, Luma’s head of product growth, had to comment on Discord

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

Developer tool! XREAL Air 2 ULTRA goes on sale, immersive experience AI development Developer tool! XREAL Air 2 ULTRA goes on sale, immersive experience AI development Aug 07, 2024 pm 06:40 PM

At 2:00 pm on July 31, Beijing time, the latest member of the XREAL series of AR glasses, XREAL Air2 Ultra, was officially launched in China. It is currently available on JD.com, Tmall, Douyin and other platforms, with an initial price of 3,999 yuan. This AR glasses is a flagship product mainly for the developer community. It aims to lower the threshold for developers to enter spatial computing, promote innovation in the field of spatial computing, and establish a more prosperous AR ecosystem. Empowering developers with six core capabilities As XREAL’s second 6DoF (Six Degrees of Freedom, six degrees of freedom) full-featured glasses, XREAL Air2 Ultra is currently the only one in the industry that uses dual environment sensing sensors (SLAM Camera)

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

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

See all articles