`
fantaxy025025
  • 浏览: 1346973 次
  • 性别: 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源码和笔记

    MongoDB是一款高性能、开源、...通过深入研究这些源码和笔记,开发者不仅可以提升对MongoDB的理解,还能学习到分布式系统设计、数据库理论和高级C++编程技巧,对于从事数据库开发或运维的人员来说,是一份宝贵的资料。

    MongoDB学习笔记

    3. 分片集群的理论、搭建过程、测试结果、优势剖析、分片键选择和集群管理:分片是MongoDB中实现数据水平扩展的关键技术。 五、数据库管理 1. 导入导出:可以将数据导出为JSON格式,也可以从JSON导入数据。 2. 数据...

    MongoDB学习总结笔记

    通过深入学习这些文档,你可以获得全面的MongoDB知识,从基础到高级,从理论到实践,从而更好地掌握这个强大的NoSQL数据库。对于初学者来说,这是一条有效的学习路径,有助于快速理解和应用MongoDB。

    mongoDB学习笔记及工具.zip

    本压缩包“mongoDB学习笔记及工具.zip”包含了一些资源,帮助你深入理解和掌握MongoDB的相关知识。 1. **笔记(note.txt)**: 这个文件可能是对MongoDB的基础概念、安装过程、基本操作和进阶特性的详细记录。笔记...

    delphi所有笔记,还有mongodb innosetup sql等

    总结来说,这些笔记涵盖了从客户端应用程序开发(Delphi)、数据库管理(MongoDB)、安装部署(InnoSetup)到数据管理(SQL)的广泛知识,对于希望全面理解软件开发流程的开发者来说是非常宝贵的资源。通过深入学习...

    免费的mongoDB

    本资源包含四篇PDF学习文档,旨在帮助初学者和进阶者全面掌握MongoDB的相关知识。 首先,"MongoDB基础教程"是入门MongoDB的最佳起点。这个教程将详细介绍MongoDB的基本概念,如数据模型、集合、文档、字段等。...

    李兴华java笔记

    《李兴华Java实战经典笔记》是一份深入探讨Java编程技术的宝贵资料,由知名IT教育专家李兴华编撰。这份笔记集合了他在教学和实践中积累的丰富经验,...同时,结合实际编程练习,可以更好地巩固理论知识,提升编程能力。

    MongoDB入门的一些资料

    MongoDB是一种流行的开源文档型数据库,它属于NoSQL数据库范畴,以其灵活性、高...在学习过程中,建议动手实践,通过创建自己的数据库和应用来巩固知识,同时不断关注MongoDB的最新发展和社区资源,以保持与时俱进。

    learning-mongodb:使用MongoDB数据库发现和学习

    "课件"和"作业"则是实践性的学习材料,通过实际操作来巩固理论知识。这些可能包括练习题、小项目或模拟测试,旨在提高你的动手能力和解决问题的能力。实践是学习数据库的最佳方式,因为它能让你亲身体验如何在真实...

    达内开发笔记

    此外,笔记可能还包含了实际项目案例分析,例如如何从需求分析到系统设计,再到编码实现和测试调试的全过程,让学习者能够将理论知识应用于实际场景。 总的来说,【达内开发笔记】是一份全面的IT技术学习资料,不仅...

    MongoDB-Coursera:该存储库包含课程中提供的测验解决方案和参考笔记本

    MongoDB 是一个流行的开源、分布式文档数据库,设计用于处理大量数据并提供高可用性和高性能。...参考笔记本和测验解决方案将为学习过程提供实践指导和问题解答,帮助巩固理论知识并提升实战技能。

    云笔记客服端

    【云笔记客户端】是一款在校园项目背景下开发的移动端应用程序,主要功能是提供便捷的云存储和同步笔记服务。...通过这样的项目,开发者不仅能学习到实际开发流程,还能深入理解如何将理论知识应用到实际产品中。

    个人笔记.zip

    可能包括了Python、Java、C++、JavaScript等主流语言的学习笔记,或者是关于函数式编程、面向对象编程的理论和实践。此外,笔记可能还涉及到框架和库的使用,例如Django、React或TensorFlow等。 数据库管理也是重要...

    新手乐园笔记(CLH) 新手乐园笔记(CLH)

    在【新手乐园笔记(CLH).txt】文件中,可能包含了上述各个主题的详细解释、实例演示和练习题,帮助新手通过实践来巩固理论知识。这份笔记不仅适合自学,也可作为课堂教学辅助材料,以引导新手逐步踏入IT世界的广阔...

    韩顺平各种课题笔记

    韩顺平老师的教学风格强调实战和实用性,因此这些笔记不仅提供了理论知识,还注重培养读者解决实际问题的能力。在学习过程中,读者应积极动手实践,将所学应用到实际项目中,这样才能真正掌握这些知识点,并在未来的...

    2009数据库系统工程师学习笔记

    2009年的数据库系统工程师学习笔记可能涵盖了当时该领域的核心概念和技术。以下是对这些笔记可能包含的一些关键知识点的详细说明: 1. **数据库基础理论**: - 数据模型:包括关系模型(如SQL)、网络模型、层次...

    这是一个基于SpringCloud + vue的云笔记系统,应用于毕业设计.zip

    数据库方面,可能会使用MySQL、MongoDB等常见数据库存储笔记内容和用户信息。此外,安全方面,系统可能采用了Spring Security或者JWT(JSON Web Tokens)进行用户认证和授权,确保了数据的安全性。 总的来说,这个...

    Spring学习笔记.zip

    为了充分利用这些笔记,建议按照顺序阅读,理解每个阶段的内容,然后实践操作以巩固理论知识。同时,使用Typora或Notepad++等Markdown阅读器可以方便地查看和编辑笔记内容。在学习过程中,可以结合实际项目练习,将...

    云笔记.zip

    5. **毕设项目**:作为毕业设计,云笔记项目提供了一个实践性的平台,学生可以在此学习如何将理论知识应用于实际开发,包括需求分析、系统设计、编码实现、测试调试和文档编写等全过程。 6. **计算机科学基础**:...

    Java架构面试专题(含答案)和学习笔记(5).rar

    以上只是Java架构面试中部分可能涉及的知识点,具体的学习笔记和答案会更加详细地解释每个概念,提供实践案例和解决思路,帮助读者巩固理论知识并提升实战技能。对于希望在Java架构领域深造的开发者来说,这是一个...

Global site tag (gtag.js) - Google Analytics