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 }
二,php创建,切换,删除数据库
1,切换数据库
$mongo = new Mongo(); $db = $mongo->selectDB('test'); //切换数据库
2,创建数据库
$mongo = new Mongo(); $db = $mongo->selectDB('test'); $users = $db->createCollection("users"); $alldb = $mongo->listDBs(); //列出所有数据库 print_r($alldb); //可以看到db创建成功了
在这里要注意一下,如果你不创建一个collection(根关系型数据库的表基本上是一样的),是创建不了数据库的。
3,删除数据库
$mongo = new Mongo(); $db = $mongo->selectDB('test'); $db->drop();
三,小节
这篇文章很简单吧,哈哈,不想在一篇文章里面写太多的东西,折开来写,看的更清楚一点,更细一点。
在这儿要提一下,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() 返回当前程序的版本信息
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() 返回数据集共享版本号
原文地址:mongodb 数据库创建,切换,删除, 感谢原作者分享。

MySQLstringtypesimpactstorageandperformanceasfollows:1)CHARisfixed-length,alwaysusingthesamestoragespace,whichcanbefasterbutlessspace-efficient.2)VARCHARisvariable-length,morespace-efficientbutpotentiallyslower.3)TEXTisforlargetext,storedoutsiderows,

MySQLstringtypesincludeVARCHAR,TEXT,CHAR,ENUM,andSET.1)VARCHARisversatileforvariable-lengthstringsuptoaspecifiedlimit.2)TEXTisidealforlargetextstoragewithoutadefinedlength.3)CHARisfixed-length,suitableforconsistentdatalikecodes.4)ENUMenforcesdatainte

MySQLoffersvariousstringdatatypes:1)CHARforfixed-lengthstrings,2)VARCHARforvariable-lengthtext,3)BINARYandVARBINARYforbinarydata,4)BLOBandTEXTforlargedata,and5)ENUMandSETforcontrolledinput.Eachtypehasspecificusesandperformancecharacteristics,sochoose

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version
