Home Database Mysql Tutorial mongodb 数据库创建,切换,删除

mongodb 数据库创建,切换,删除

Jun 07, 2016 pm 04:33 PM
mongodb switch create delete database

mongodb是nosql里面最像关系型数据库的数据库。单表操作,基本上可以和关系型数据库差不多。mongodb比较易学,易用,分几期记录一下,学习和使用mongodb过程。mongodb安装就不说了,请参考: centos yum 安装 mongodb 以及php扩展 一,创建,切换,删除数据

mongodb是nosql里面最像关系型数据库的数据库。单表操作,基本上可以和关系型数据库差不多。mongodb比较易学,易用,分几期记录一下,学习和使用mongodb过程。mongodb安装就不说了,请参考:centos yum 安装 mongodb 以及php扩展

一,创建,切换,删除数据库

[root@localhost zhangy]# mongo
MongoDB shell version: 2.4.6
connecting to: tank
> use test            //创建 or 切换数据库
switched to db test
> db.dropDatabase()   //删除数据库
{ "dropped" : "test", "ok" : 1 }
Copy after login

二,php创建,切换,删除数据库

1,切换数据库

$mongo = new Mongo();
$db = $mongo->selectDB('test');   //切换数据库
Copy after login

2,创建数据库

$mongo = new Mongo();
$db = $mongo->selectDB('test');
$users = $db->createCollection("users");
$alldb = $mongo->listDBs();  //列出所有数据库
print_r($alldb);           //可以看到db创建成功了
Copy after login

在这里要注意一下,如果你不创建一个collection(根关系型数据库的表基本上是一样的),是创建不了数据库的。

3,删除数据库

$mongo = new Mongo();
$db = $mongo->selectDB('test');
$db->drop();
Copy after login

三,小节

这篇文章很简单吧,哈哈,不想在一篇文章里面写太多的东西,折开来写,看的更清楚一点,更细一点。

在这儿要提一下,mongodb命令下的帮助,这个对于命令行操作很有帮助。

1,db的帮助

db.AddUser(username,password)  添加用户
db.auth(usrename,password)     设置数据库连接验证
db.cloneDataBase(fromhost)     从目标服务器克隆一个数据库
db.commandHelp(name)           returns the help for the command
db.copyDatabase(fromdb,todb,fromhost)  复制数据库fromdb---源数据库名称,todb---目标数据库名称,fromhost---源数据库服务器地址
db.createCollection(name,{size:3333,capped:333,max:88888})  创建一个数据集,相当于一个表
db.currentOp()                 取消当前库的当前操作
db.dropDataBase()              删除当前数据库
db.eval(func,args)             run code server-side
db.getCollection(cname)        取得一个数据集合,同用法:db['cname'] or
db.getCollenctionNames()       取得所有数据集合的名称列表
db.getLastError()              返回最后一个错误的提示消息
db.getLastErrorObj()           返回最后一个错误的对象
db.getMongo()                  取得当前服务器的连接对象get the server
db.getMondo().setSlaveOk()     allow this connection to read from then nonmaster membr of a replica pair
db.getName()                   返回当操作数据库的名称
db.getPrevError()              返回上一个错误对象
db.getProfilingLevel()         获取profile level
db.getReplicationInfo()        获得重复的数据
db.getSisterDB(name)           get the db at the same server as this onew
db.killOp()                    停止(杀死)在当前库的当前操作
db.printCollectionStats()      返回当前库的数据集状态
db.printReplicationInfo()        打印主数据库的复制状态信息
db.printSlaveReplicationInfo()        打印从数据库的复制状态信息
db.printShardingStatus()       返回当前数据库是否为共享数据库
db.removeUser(username)        删除用户
db.repairDatabase()            修复当前数据库
db.resetError()
db.runCommand(cmdObj)          run a database command. if cmdObj is a string, turns it into {cmdObj:1}
db.setProfilingLevel(level)    设置profile level 0=off,1=slow,2=all
db.shutdownServer()            关闭当前服务程序
db.version()                   返回当前程序的版本信息
Copy after login

2,表的帮助,格式,db.表名.help()

db.test.find({id:10})          返回test数据集ID=10的数据集
db.test.find({id:10}).count()  返回test数据集ID=10的数据总数
db.test.find({id:10}).limit(2) 返回test数据集ID=10的数据集从第二条开始的数据集
db.test.find({id:10}).skip(8)  返回test数据集ID=10的数据集从0到第八条的数据集
db.test.find({id:10}).limit(2).skip(8)  返回test数据集ID=1=的数据集从第二条到第八条的数据
db.test.find({id:10}).sort()   返回test数据集ID=10的排序数据集
db.test.findOne([query])       返回符合条件的一条数据
db.test.getDB()                返回此数据集所属的数据库名称
db.test.getIndexes()           返回些数据集的索引信息
db.test.group({key:...,initial:...,reduce:...[,cond:...]})    返回分组信息
db.test.mapReduce(mayFunction,reduceFunction,)  这个有点像存储过程
db.test.remove(query)                      在数据集中删除一条数据
db.test.renameCollection(newName)          重命名些数据集名称
db.test.save(obj)                          往数据集中插入一条数据
db.test.stats()                            返回此数据集的状态
db.test.storageSize()                      返回此数据集的存储大小
db.test.totalIndexSize()                   返回此数据集的索引文件大小
db.test.totalSize()                        返回些数据集的总大小
db.test.update(query,object[,upsert_bool]) 在此数据集中更新一条数据
db.test.validate()                         验证此数据集
db.test.getShardVersion()                  返回数据集共享版本号
Copy after login
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)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1263
29
C# Tutorial
1237
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:

Oracle's Role in the Business World Oracle's Role in the Business World Apr 23, 2025 am 12:01 AM

Oracle is not only a database company, but also a leader in cloud computing and ERP systems. 1. Oracle provides comprehensive solutions from database to cloud services and ERP systems. 2. OracleCloud challenges AWS and Azure, providing IaaS, PaaS and SaaS services. 3. Oracle's ERP systems such as E-BusinessSuite and FusionApplications help enterprises optimize operations.

MySQL vs. Other Databases: Comparing the Options MySQL vs. Other Databases: Comparing the Options Apr 15, 2025 am 12:08 AM

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.

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.

MySQL: Structured Data and Relational Databases MySQL: Structured Data and Relational Databases Apr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

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

MySQL: A Beginner-Friendly Approach to Data Storage MySQL: A Beginner-Friendly Approach to Data Storage Apr 17, 2025 am 12:21 AM

MySQL is suitable for beginners because it is easy to use and powerful. 1.MySQL is a relational database, and uses SQL for CRUD operations. 2. It is simple to install and requires the root user password to be configured. 3. Use INSERT, UPDATE, DELETE, and SELECT to perform data operations. 4. ORDERBY, WHERE and JOIN can be used for complex queries. 5. Debugging requires checking the syntax and use EXPLAIN to analyze the query. 6. Optimization suggestions include using indexes, choosing the right data type and good programming habits.

See all articles