Home Database Mysql Tutorial MongoDB简单的增、删、改、查

MongoDB简单的增、删、改、查

Jun 07, 2016 pm 04:41 PM
drop insert mongodb remove Simple

insert、remove、drop、update、find、show dbs、show tables先用一段简单的实际操作阐述下使用方法,再较详细的分析。 Linux下执行mongodb自带的mongo命令就可以进入类似mysql一样的控制界面,mongodb的数据库、集合、文档类似mysql中的数据库、表、记录的

insert、remove、drop、update、find、show dbs、show tables先用一段简单的实际操作阐述下使用方法,再较详细的分析。
Linux下执行mongodb自带的mongo命令就可以进入类似mysql一样的控制界面,mongodb的数据库、集合、文档类似mysql中的数据库、表、记录的概念,下面上干货。

#查看数据库
> show dbs;
admin   (empty)
local   0.078GB
myinfo  0.078GB

#切换数据库,如果数据库不存在,将会在增加第一条记录时自动创建该数据库
> use myinfo
switched to db myinfo

#查看集合,在向一个不存在的集合添加文档的时自动创建该集合
> show tables;
system.indexes

#定义一个文档
> doc01={'id':'10', 'name':'job', 'doc':'hello world!'}
{ "id" : "10", "name" : "job", "doc" : "hello world!" }

#查看文档
> doc01
{ "id" : "10", "name" : "job", "doc" : "hello world!" }

#将文档插入testtable集合
> db.testtable.insert(doc01)
WriteResult({ "nInserted" : 1 })

#也可以向集合直接插入文档
> db.testtable.insert({'id':'11', 'name':'jim', 'doc':'hi world!'})
WriteResult({ "nInserted" : 1 })

#再次查看集合时,会发现新创建的集合testtable
> show tables;
system.indexes
testtable

#查找集合testtable中的所有文档
> db.testtable.find()
{ "_id" : ObjectId("5476cd8e0074a24d1b6eaea7"), "id" : "10", "name" : "job", "doc" : "hello world!" }
{ "_id" : ObjectId("5476cdc00074a24d1b6eaea8"), "id" : "11", "name" : "jim", "doc" : "hi world!" }

#查找id为11的文档
>db.testtable.find({'id':'11'})
{ "_id" : ObjectId("5476cdc00074a24d1b6eaea8"), "id" : "11", "name" : "jim", "doc" : "hi world!" }

#更新id为10的文档,将name改为kiki
>  db.testtable.update({'id':'10'},{'id':'10', 'name':'kiki', 'doc':'hello workd!'})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.testtable.find()
{ "_id" : ObjectId("5476cd8e0074a24d1b6eaea7"), "id" : "10", "name" : "kiki", "doc" : "hello workd!" }
{ "_id" : ObjectId("5476cdc00074a24d1b6eaea8"), "id" : "11", "name" : "jim", "doc" : "hi world!" }

#将id等于10的文档删除
> db.testtable.remove({'id':'10'})
WriteResult({ "nRemoved" : 1 })
> db.testtable.find()
{ "_id" : ObjectId("5476cdc00074a24d1b6eaea8"), "id" : "11", "name" : "jim", "doc" : "hi world!" }
>
Copy after login

insert( )函数
使用比较简单,直接插入或间接插入已定义的文档即可。
update( )函数

     db.collection.update( criteria, objNew, upsert, multi )
     update()函数接受以下四个参数:
          criteria : update的查询条件,类似sql update查询内where后面的。
          objNew : update的对象和一些更新的操作符(如$,$inc...)等,也可以理解为sql update查询内set后面的
          upsert : 这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。
          multi : mongodb默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。
Copy after login

remove( )函数、dorp( )函数

     使用 remove() 函数移除数据
          如果你想移除"userdetails"集合中"user_id" 为 "testuser"的数据你可以执行以下命令:
          >db.userdetails.remove( { "user_id" : "testuser" } )
     删除所有数据
          如果你想删除"userdetails"集合中的所有数据,可以执行以下命令:
          >db.userdetails.remove({})
     使用drop()删除集合
          如果你想删除整个"userdetails"集合,包含所有文档数据,可以执行以下数据:
          >db.userdetails.drop()
     使用dropDatabase()函数删除数据库
          如果你想删除整个数据库的数据,你可以执行以下命令:
          >db.dropDatabase()
Copy after login

find( )函数

 从集合中获取数据
          如果你想在集合中读取所有的的数据,可以执行以下命令
          >db.userdetails.find();
          类似于如下SQL查询语句:
          Select * from userdetails;
     通过指定条件读取数据
          如果我们想在集合"userdetails"中读取"education"为"M.C.A." 的数据,我们可以执行以下命令:
          >db.userdetails.find({"education":"M.C.A."})
          类似如下SQL查询语句:
          Select * from userdetails where education="M.C.A.";
     通过条件操作符读取数据
          MongoDB中条件操作符有:
               (>) 大于 - $gt
               (=) 大于等于 - $gte
               () 大于操作符 - $gt
          如果你想获取"testtable"集合中"age" 大于22的数据,你可以使用以下命令:
          >db.testtable.find({age : {$gt : 22}})
          类似于SQL语句:
          Select * from testtable where age >22;

          MongoDB 使用 () 查询operator - $lt 和 $gt
          如果你想获取"testtable"集合中"age" 大于17以及小于24的数据,你可以执行以下命令:
          >db.testtable.find({age : {$lt :24, $gt : 17}})

     更多的查询技巧可以查看http://www.w3cschool.cc/mongodb/mongodb-query.html
Copy after login

文章出处:http://www.xiaomastack.com/2014/11/29/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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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
1269
29
C# Tutorial
1248
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 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.

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

See all articles