`
fantaxy025025
  • 浏览: 1247122 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类

Mongodb理论知识和使用笔记

 
阅读更多

Mongodb理论知识,小记,笔记,小结,总结 

 

基本概念对比关系数据库(以mysql来讲)

# 文档document对应mysql的记录row,文档保存为BSON格式,大小不能超过4MB(2013-08现在版本支持到16M了)

# 集合collection对应mysql表table,多个document组成collection,相当于mysql的多行组成table一样

# 多个集合collection组成数据库database

# 多个数据库可以在一个mongo实例中,相当于安装的一个mysql中可以有多个database一样

小结:

一切都是文件

# mysql中,行是最小单位,行组成表,表组成db,多个db可以在一个myslq实例中;

# mongodb中也一样,只不过最小单位叫document,document组成collection,多个collection组成database,一个mongo实例可以有多个database

从上面的饿对比来看,没啥区别。

但最大的区别就是nosql的本质,即存储的最小单位没有了固定的结构!mysql中的row,不管有没有值,都是一样的,字段个数,格式都一样。而mongodb中就不同了,最小的单位没有固定的格式,从而也就 no sql 了。

 

语法体系为JavaScript,很多效仿Mysql

数据类型也基本为js

自带js的shell

客户端启动默认链接test库,并且把db变量赋值为test

 

update操作不返回结果(默认)

插入,删除,更新,这3个操作都不需要等待数据库响应并返回结果,这个特点的好处是快,坏处是不安全,有问题也不知道,可以用getLastError来检查,安全版本自动执行这个检查。

mongo默认是采用的不安全(离玄之箭),开发最好选用安全版本,可以及时发现问题。

 

给每个连接都分配一个队列

队列就会排队,这样一个连接发出去的请求是被顺序执行的;

但是,不同的连接,执行顺序不能保证,也就是会出现这个情况:一个连接发送请求插入了一条记录,另一个连接不一定能读出来。

这个在使用ruby,java,python等连接池的时候需要特别注意! 连接池导致每次请求可能拿到了不同的链接。

 

基本操作规则

大小写敏感。

db:代表的是当前的数据库

show dbs : 显示出当前的数据库名称。--mysql--show databases;

show collections 显示出当前数据库中的表。 --mysql-- show tables;

 

insert

添加记录  --insert

1. 向用户表(user)中添加一条记录

var user = { username:Tomage:10 };  ----》对象  (json)

db.user.insert(user);               --------》 user(集合)中插入记录

 

2. 或者直接插入一条数据:

    Db.user.insert({name:zhangsan,age:10});

     ---insert into user (name,age) values(zhangsan,10);

 

3. 向用户集合中插入一条日志记录

var blog = {title:title1,content:content1,addtime:2012}

db.user.insert(blog);

 

read

查询记录 -> find()   ->findOne()

db.user.findOne()  à 查询出第一条记录 ------> select * from users limit 1

db.user.find()   à 查询出所有的记录------->select * from users 

 

条件查询:

查询出年龄等于10岁所有记录

db.user.find( { age:10 } )  --------->select * from users where age=10

查询出年龄等于10岁并且姓名是“tom所有记录

db.user.find( { age:10,username:Tom } ) ---->select * from users where usersname=tom and age=10

 

Mongodb中的限制查询,排序,记录数(可用于分页的功能)

 

限制查询的功能:(对应的sql语句)

1.db.users.find().limit(10)---------->select * from users limit 0,10;

 Db.users.find().skip(3).limit(10)---------->select * from users limit 3,10;

Skip() 函数表示的是跳过几条记录

 

2.查找总的记录数:

 Db.users.find().count() -------->select count(*) from users

 

Db.users.find({name:zhangsan}).count()------->selec count(*) from users where name=zhangsan

 

3.对相应的记录进行排序:

Db.users.find().sort({age:-1})------>select * from users order by age desc 

Db.users.find().sort({age:1})-------->select * from users order by age asc

注意:表示的是升序,-1表示的是降序

 

4.还有一个查询功能:

 Db.users.find(this.age>13) ------->select * from users where age>13

 Db.users.find(this.age>13,{name:1})----->select name from users where age>13

 上面的这种查询方式,不能用于查询 相等 的情况

 

5.查询带有范围的数据:

 Db.users.find({age:{$in:[13,23,33]}})----->select * from users where age in 13,23,33

 上面的$in 还是可以变换的,例如:$lt $gt $gte $lte $eq $ne等一些范围的修饰符

 

update

修改记录  update(where,data)  ,  save()

修改Tom年龄为20?

var u = db.user.findOne( {“username:Tom”})

u.age = 20

db.user.save(u);

上面的这种做法也是错误的 

 

错误:

db.user.update( {username:Tom}  ,  {age:20} )    à  注意,错误!

正确:

var u = db.user.findOne( {“username:Tom”})

u.age = 20

db.user.update({username:Tom}  , u )---------->也是错误的

还可以这样的更改数据:

Db.users.update({name:zhangsan},{$set:{age:15}}) 

 

delete

删除记录     remove()

删除所有的记录:

db.user.remove(); ------delete * from user

删除age=30的记录

db.user.remove({age:30}) --->delete from user where age=30

 

删除年龄小于20岁的记录

Db.users.remove({age:{$lt:20}}) ----->delete from users where age<20

上面的$lt也是可以变换的,例如:$gt $eq $ne $gte $lte

 

再删除的时候,如果添加的时候,数据是有引号的,则在删除的时候,也是必须加上引号的 

 

寻求帮助--mysql--?

Mysql中常用的就是问号来找出帮助

例如:

mysql> ?

 

For information about MySQL products and services, visit:

   http://www.mysql.com/

For developer information, including the MySQL Reference Manual, visit:

   http://dev.mysql.com/

To buy MySQL Enterprise support, training, or other products, visit:

   https://shop.mysql.com/

 

List of all MySQL commands:

Note that all text commands must be first on line and end with ';'

?         (\?) Synonym for `help'.

clear     (\c) Clear the current input statement.

connect   (\r) Reconnect to the server. Optional arguments are db and host.

delimiter (\d) Set statement delimiter.

edit      (\e) Edit command with $EDITOR.

ego       (\G) Send command to mysql server, display result vertically.

exit      (\q) Exit mysql. Same as quit.

go        (\g) Send command to mysql server.

help      (\h) Display this help.

nopager   (\n) Disable pager, print to stdout.

notee     (\t) Don't write into outfile.

pager     (\P) Set PAGER [to_pager]. Print the query results via PAGER.

print     (\p) Print current command.

prompt    (\R) Change your mysql prompt.

quit      (\q) Quit mysql.

rehash    (\#) Rebuild completion hash.

source    (\.) Execute an SQL script file. Takes a file name as an argument.

status    (\s) Get status information from the server.

system    (\!) Execute a system shell command.

tee       (\T) Set outfile [to_outfile]. Append everything into given outfile.

use       (\u) Use another database. Takes database name as argument.

charset   (\C) Switch to another charset. Might be needed for processing binlog with multi-byte charsets.

warnings  (\W) Show warnings after every statement.

nowarning (\w) Don't show warnings after every statement.

 

For server side help, type 'help contents' 

 

Mysql中查看某个命令的帮助

mysql> ? create index

Name: 'CREATE INDEX'

Description:

Syntax:

CREATE [ONLINE|OFFLINE] [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name

    [index_type]

    ON tbl_name (index_col_name,...)

    [index_option] ...

 

index_col_name:

    col_name [(length)] [ASC | DESC]

 

index_type:

    USING {BTREE | HASH}

 

index_option:

    KEY_BLOCK_SIZE [=] value

  | index_type

  | WITH PARSER parser_name

  | COMMENT 'string'

 

CREATE INDEX is mapped to an ALTER TABLE statement to create indexes.

See [HELP ALTER TABLE]. CREATE INDEX cannot be used to create a PRIMARY

KEY; use ALTER TABLE instead. For more information about indexes, see

http://dev.mysql.com/doc/refman/5.5/en/mysql-indexes.html.

 

URL: http://dev.mysql.com/doc/refman/5.5/en/create-index.html

 

Mongodb中,用help命令来看帮助:

系统级帮助: help //系统级的,这个设计很差!不一致是个大毛病,起码不能解放大脑,看下面就知道了

数据库级:  db.help()  //这两个是个函数,有括号

集合级: db.user.help() //这两个是个函数,有括号

函数级:db.user.insert  //这里没有括号,将直接看见这个函数的源码;注意这里insert没有可用的help函数

系统级的help

> help

db.help()                    help on db methods

db.mycoll.help()             help on collection methods

sh.help()                    sharding helpers

rs.help()                    replica set helpers

help admin                   administrative help

help connect                 connecting to a db help

help keys                    key shortcuts

help misc                    misc things to know

help mr                      mapreduce

 

show dbs                     show database names

show collections             show collections in current database

show users                   show users in current database

show profile                 show most recent system.profile entries with time >= 1ms

show logs                    show the accessible logger names

show log [name]              prints out the last segment of log in memory, 'global' is default

use <db_name>                set current database

db.foo.find()                list objects in collection foo

db.foo.find( { a : 1 } )     list objects in foo where a == 1

it                           result of the last line evaluated; use to further iterate

DBQuery.shellBatchSize = x   set default number of items to display on shell

exit                         quit the mongo shell

 

 

database的helop

> db.help()

DB methods:

db.addUser(userDocument)

db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [ just calls db.runCommand(...) ]

db.auth(username, password)

db.cloneDatabase(fromhost)

db.commandHelp(name) returns the help for the command

db.copyDatabase(fromdb, todb, fromhost)

db.createCollection(name, { size : ..., capped : ..., max : ... } )

db.currentOp() displays currently executing operations in the db

db.dropDatabase()

db.eval(func, args) run code server-side

db.fsyncLock() flush data to disk and lock server for backups

db.fsyncUnlock() unlocks server following a db.fsyncLock()

db.getCollection(cname) same as db['cname'] or db.cname

db.getCollectionNames()

db.getLastError() - just returns the err msg string

db.getLastErrorObj() - return full status object

db.getMongo() get the server connection object

db.getMongo().setSlaveOk() allow queries on a replication slave server

db.getName()

db.getPrevError()

db.getProfilingLevel() - deprecated

db.getProfilingStatus() - returns if profiling is on and slow threshold

db.getReplicationInfo()

db.getSiblingDB(name) get the db at the same server as this one

db.hostInfo() get details about the server's host

db.isMaster() check replica primary status

db.killOp(opid) kills the current operation in the db

db.listCommands() lists all the db commands

db.loadServerScripts() loads all the scripts in db.system.js

db.logout()

db.printCollectionStats()

db.printReplicationInfo()

db.printShardingStatus()

db.printSlaveReplicationInfo()

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

db.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=all

db.setVerboseShell(flag) display extra information in shell output

db.shutdownServer()

db.stats()

db.version() current version of the server

 

#collections的help

> db.users.help()

DBCollection help

db.users.find().help() - show DBCursor help

db.users.count()

db.users.copyTo(newColl) - duplicates collection by copying all documents to newColl; no indexes are copied.

db.users.convertToCapped(maxBytes) - calls {convertToCapped:'users', size:maxBytes}} command

db.users.dataSize()

db.users.distinct( key ) - e.g. db.users.distinct( 'x' )

db.users.drop() drop the collection

db.users.dropIndex(index) - e.g. db.users.dropIndex( "indexName" ) or db.users.dropIndex( { "indexKey" : 1 } )

db.users.dropIndexes()

db.users.ensureIndex(keypattern[,options]) - options is an object with these possible fields: name, unique, dropDups

db.users.reIndex()

db.users.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.

                                             e.g. db.users.find( {x:77} , {name:1, x:1} )

db.users.find(...).count()

db.users.find(...).limit(n)

db.users.find(...).skip(n)

db.users.find(...).sort(...)

db.users.findOne([query])

db.users.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } )

db.users.getDB() get DB object associated with collection

db.users.getIndexes()

db.users.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )

db.users.insert(obj)

db.users.mapReduce( mapFunction , reduceFunction , <optional params> )

db.users.remove(query)

db.users.renameCollection( newName , <dropTarget> ) renames the collection.

db.users.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name

db.users.save(obj)

db.users.stats()

db.users.storageSize() - includes free space allocated to this collection

db.users.totalIndexSize() - size in bytes of all the indexes

db.users.totalSize() - storage allocated for all data and indexes

db.users.update(query, object[, upsert_bool, multi_bool]) - instead of two flags, you can pass an object with fields: upsert, multi

db.users.validate( <full> ) - SLOW

db.users.getShardVersion() - only for use with sharding

db.users.getShardDistribution() - prints statistics about data distribution in the cluster

db.users.getSplitKeysForChunks( <maxChunkSize> ) - calculates split points over all chunks and returns splitter function

 

 

prefer:

http://blog.sina.com.cn/s/blog_c274583b0101be9a.html

 

 

--完毕--

--完毕--

--完毕--

000000

--完毕--

--完毕--

--完毕--

 

 

分享到:
评论

相关推荐

    MongoDB笔记.docx

    7、MongoDB模糊查询和其他条件查询 12 五、Mongoose(node使用)(前提安装好node环境有node基础) 13 1、连接 13 2、创建模式结构(Schema)定义约束了数据库中的文档结构 14 3、通过Schema来创建Model相当于mongoDB...

    《mongodb入门》读书笔记

    《mongodb入门》读书笔记

    MongoDB 入门教程笔记

    MongoDB 入门教程笔记

    MongoDB_学习笔记

    MongoDB_学习笔记MongoDB_学习笔记MongoDB_学习笔记MongoDB_学习笔记MongoDB_学习笔记MongoDB_学习笔记MongoDB_学习笔记MongoDB_学习笔记MongoDB_学习笔记MongoDB_学习笔记MongoDB_学习笔记MongoDB_学习笔记MongoDB_...

    mongodb学习笔记

    mongodb学习笔记

    mongodb group aggregate项目实战笔记

    mongodb group aggregate项目实战笔记 管道聚合 mongodb group按时间分组,用aggregate管道聚合 会比group的处理效率要高而且更灵活方便

    MongoDB学习笔记

    这是本人自己在学习过程中作的一些笔记,有利于初学者迅速掌握MongoDB的基本概念和操作。

    《MongoDB权威指南》读书笔记1

    《MongoDB权威指南》读书笔记1

    mongodb学习笔记和mongodb权威指南

    mongodb学习资料,包括mongodb_and_python学习笔记、mongodb权威指南、mongodb学习手册、mongodb总结。

    mongoDb源码和笔记

    mongoDb详细笔记和源码,如果对mongoDb感兴趣的可以好好看看源码

    MongoDB使用手册

    MongoDB使用手册MongoDB使用手册MongoDB使用手册MongoDB使用手册MongoDB使用手册MongoDB使用手册MongoDB使用手册

    mongodb笔记

    此笔记是我个人通过自学整理出来的。希望看到的人有什么建议告诉我。也可以共同去学习!里面内容包括:安装配置、增删改查、用户管理、主从复制、分片、副本集以及和JAVA的结合案例等等!

    MongoDB3.2实战笔记

    MongoDB3.2实战笔记

    MongoDB数据库-163 李兴华培训笔记.rar

    网易云课堂-『李兴华java培训23』MongoDB数据库-笔记 最后2节因为是JAVA开发环境,因为没有使用JAVA开发,所有使用的是截图。 基础课,没有哪么多的废话,听听还不错。

    Mongodb基础知识详解(值得珍藏).pdf

    MongoDB使用文档结构来存储数据,这与其他关系型数据库有很大的不同。通过了解文档结构和数据模型,开发人员可以更有效地设计数据库模式和表结构,以适应应用程序的需求。 其次,掌握MongoDB基础知识有助于提高开发...

    MongoDB java使用文档

    MongoDB实现增删改查,java程序驱动,复杂查询,源代码示例

    mongodb学习笔记资料

    mongodb学习笔记资料,从安装到操作库collection 对document的crud 索引 replicaSet sharding 备份与恢复

    MongoDB学习笔记思维导图.pdf

    MongoDB学习笔记思维导图.pdf

Global site tag (gtag.js) - Google Analytics