Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2566365
  • 博文数量: 245
  • 博客积分: 4125
  • 博客等级: 上校
  • 技术积分: 3113
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-25 23:56
文章分类

全部博文(245)

文章存档

2015年(2)

2014年(26)

2013年(41)

2012年(40)

2011年(134)

2010年(2)

分类: 数据库开发技术

2012-12-25 10:14:39

使用mongodb进行增删改查等基本操作。本例使用 mongodb-win32-i386-2.0.8 , 在windows xp下进行测试。 MongoDB客户端和服务端都运行在本地(同一台机器)。

1.安装MongoDB

1.1.下载mongodb,并解压,本例安装在D:\J2ee\mongodb-win32-i386-2.0.8

1.2.使用mongod.exe启动mongodb

$MongoDB-folder/bin/mongod


点击(此处)折叠或打开

  1. D:\J2ee\mongodb-win32-i386-2.0.8\bin>mongod
  2. mongod --help for help and startup options
  3. Mon Dec 24 14:56:35
  4. Mon Dec 24 14:56:35 warning: 32-bit servers don't have journaling enabled by def
  5. ault. Please use --journal if you want durability.
  6. Mon Dec 24 14:56:35
  7. Mon Dec 24 14:56:35 [initandlisten] MongoDB starting : pid=1452 port=27017 dbpat
  8. h=/data/db 32-bit host=chenzhengwei
  9. Mon Dec 24 14:56:35 [initandlisten]
  10. Mon Dec 24 14:56:35 [initandlisten] ** NOTE: when using MongoDB 32 bit, you are
  11. limited to about 2 gigabytes of data
  12. Mon Dec 24 14:56:35 [initandlisten] ** see http://blog.mongodb.org/post/13
  13. 7788967/32-bit-limitations
  14. Mon Dec 24 14:56:35 [initandlisten] ** with --journal, the limit is lower
  15. Mon Dec 24 14:56:35 [initandlisten]
  16. Mon Dec 24 14:56:35 [initandlisten] db version v2.0.8, pdfile version 4.5
  17. Mon Dec 24 14:56:35 [initandlisten] git version: a340a57af7cdda865da420704e1d1b2
  18. fac0cedc2
  19. Mon Dec 24 14:56:35 [initandlisten] build info: windows sys.getwindowsversion(ma
  20. jor=6, minor=0, build=6002, platform=2, service_pack='Service Pack 2') BOOST_LIB
  21. _VERSION=1_42
  22. Mon Dec 24 14:56:35 [initandlisten] options: {}
  23. Mon Dec 24 14:56:35 [initandlisten] exception in initAndListen: 10296 dbpath (/d
  24. ata/db) does not exist, terminating
  25. Mon Dec 24 14:56:35 dbexit:
  26. Mon Dec 24 14:56:35 [initandlisten] shutdown: going to close listening sockets..
  27. .
  28. Mon Dec 24 14:56:35 [initandlisten] shutdown: going to flush diaglog...
  29. Mon Dec 24 14:56:35 [initandlisten] shutdown: going to close sockets...
  30. Mon Dec 24 14:56:35 [initandlisten] shutdown: waiting for fs preallocator...
  31. Mon Dec 24 14:56:35 [initandlisten] shutdown: closing all files...
  32. Mon Dec 24 14:56:35 [initandlisten] closeAllFiles() finished
  33. Mon Dec 24 14:56:35 dbexit: really exiting now

以上并没有启动mongod,抛出了以下异常信息:


点击(此处)折叠或打开

  1. Mon Dec 24 14:56:35 [initandlisten] exception in initAndListen: 10296 dbpath (/d
  2. ata/db) does not exist, terminating

即dbpath(/data/db)不存在

正确方法,创建目录D:\J2ee\mongodb-win32-i386-2.0.8\data,用于mongodb存放数据。

执行以下命令:


点击(此处)折叠或打开

  1. D:\J2ee\mongodb-win32-i386-2.0.8\bin>mongod -dbpath D:\J2ee\mongodb-win32-i386-2
  2. .0.8\data
  3. Mon Dec 24 15:17:03
  4. Mon Dec 24 15:17:03 warning: 32-bit servers don't have journaling enabled by def
  5. ault. Please use --journal if you want durability.
  6. Mon Dec 24 15:17:03
  7. Mon Dec 24 15:17:03 [initandlisten] MongoDB starting : pid=5884 port=27017 dbpat
  8. h=D:\J2ee\mongodb-win32-i386-2.0.8\data 32-bit host=chenzhengwei
  9. Mon Dec 24 15:17:03 [initandlisten]
  10. Mon Dec 24 15:17:03 [initandlisten] ** NOTE: when using MongoDB 32 bit, you are
  11. limited to about 2 gigabytes of data
  12. Mon Dec 24 15:17:03 [initandlisten] ** see http://blog.mongodb.org/post/13
  13. 7788967/32-bit-limitations
  14. Mon Dec 24 15:17:03 [initandlisten] ** with --journal, the limit is lower
  15. Mon Dec 24 15:17:03 [initandlisten]
  16. Mon Dec 24 15:17:03 [initandlisten] db version v2.0.8, pdfile version 4.5
  17. Mon Dec 24 15:17:03 [initandlisten] git version: a340a57af7cdda865da420704e1d1b2
  18. fac0cedc2
  19. Mon Dec 24 15:17:03 [initandlisten] build info: windows sys.getwindowsversion(ma
  20. jor=6, minor=0, build=6002, platform=2, service_pack='Service Pack 2') BOOST_LIB
  21. _VERSION=1_42
  22. Mon Dec 24 15:17:03 [initandlisten] options: { dbpath: "D:\J2ee\mongodb-win32-i3
  23. 86-2.0.8\data" }
  24. Mon Dec 24 15:17:03 [initandlisten] waiting for connections on port 27017
  25. Mon Dec 24 15:17:03 [websvr] admin web console waiting for connections on port 2
  26. 8017

2. 连接MongoDB

再打开一个命令行,执行以下mongo命令:


点击(此处)折叠或打开

  1. D:\J2ee\mongodb-win32-i386-2.0.8\bin>mongo
  2. MongoDB shell version: 2.0.8
  3. connecting to: test
  4. >

3. 创建数据库和表

mongodb中使用以下命令,切换到某个数据库(即使它还不存在)

use database-name

mongodb中当你往一个表里面插入一条记录时,相应的表和数据库就被自动创建好了。具体看下面的例子:


点击(此处)折叠或打开

  1. D:\J2ee\mongodb-win32-i386-2.0.8\bin>mongo
  2. MongoDB shell version: 2.0.8
  3. connecting to: test
  4. > use mydb
  5. switched to db mydb
  6. > db.users.insert({username:"henry",password:"123456"})
  7. > db.users.find()
  8. { "_id" : ObjectId("50d803393cc996b4e8ce22de"), "username" : "henry", "password"
  9. : "123456" }
  10. >

以下是三个常用的命令

点击(此处)折叠或打开

  1. show dbs – List all databases.
  2. use db_name – Switches to db_name.
  3. show collections – List all tables in the current selected database.


点击(此处)折叠或打开

  1. > show dbs
  2. local (empty)
  3. mydb 0.03125GB
  4. > use mydb
  5. switched to db mydb
  6. > show collections
  7. system.indexes
  8. users
  9. >

Note

In MongoDB, collection means table in SQL.

4. 插入一条记录

插入记录的语法的两种方式:


点击(此处)折叠或打开

  1. db.tablename.insert({data}) or db.tablename.save({data})

点击(此处)折叠或打开

  1. > db.users.save({username:"google",password:"google123"})
  2. > db.users.find()
  3. { "_id" : ObjectId("50d803393cc996b4e8ce22de"), "username" : "henry", "password": "123456" }
  4. { "_id" : ObjectId("50d8046a3cc996b4e8ce22df"), "username" : "google", "password" : "google123" }

5. 更新记录

更新一条记录语法:

db.tablename.update({criteria},{$set: {new value}}).

下面的例子中更新用户henry的密码:


点击(此处)折叠或打开

  1. > db.users.update({username:"henry"},{$set:{password:"henry123456"}})
  2. > db.users.find()
  3. { "_id" : ObjectId("50d8046a3cc996b4e8ce22df"), "username" : "google", "password" : "google123" }
  4. { "_id" : ObjectId("50d803393cc996b4e8ce22de"), "password" : "henry123456", "username" : "henry" }
  5. >

6. 查询记录

查找记录的语法:

db.tablename.find({criteria}).

6.1 列出users表中的所有记录


点击(此处)折叠或打开

  1. > db.users.find()
  2. { "_id" : ObjectId("50d8046a3cc996b4e8ce22df"), "username" : "google", "password" : "google123" }
  3. { "_id" : ObjectId("50d803393cc996b4e8ce22de"), "password" : "henry123456", "username" : "henry" }
  4. >

6.2 查询username 为henry的记录


点击(此处)折叠或打开

  1. > db.users.find({username:"henry"})
  2. { "_id" : ObjectId("50d803393cc996b4e8ce22de"), "password" : "henry123456", "username" : "henry" }

7. 删除记录

删除记录的语法:

db.tablename.remove({criteria}).

下面的例子


点击(此处)折叠或打开

  1. > db.users.remove({username:"google"})
  2. > db.users.find()
  3. { "_id" : ObjectId("50d803393cc996b4e8ce22de"), "password" : "henry123456", "username" : "henry" }
  4. >

Note

To delete all records from a table, uses db.tablename.remove().
To drop the table, uses db.tablename.drop().

8. 索引

Index(索引)可以提高查询的效率

8.1 List all indexes of table “users”, by default the column “_id” is always the primary key and created automatically.


点击(此处)折叠或打开

  1. > db.users.getIndexes()
  2. [
  3. {
  4. "v" : 1,
  5. "key" : {
  6. "_id" : 1
  7. },
  8. "ns" : "mydb.users",
  9. "name" : "_id_"
  10. }
  11. ]
  12. >

8.2 To create an index, uses db.tablename.ensureIndex(column). In below example, an index is created on column “username”.


点击(此处)折叠或打开

  1. > db.users.ensureIndex({username:1})
  2. > db.users.getIndexes()
  3. [
  4. {
  5. "v" : 1,
  6. "key" : {
  7. "_id" : 1
  8. },
  9. "ns" : "mydb.users",
  10. "name" : "_id_"
  11. },
  12. {
  13. "v" : 1,
  14. "key" : {
  15. "username" : 1
  16. },
  17. "ns" : "mydb.users",
  18. "name" : "username_1"
  19. }
  20. ]
  21. >

8.3 To drop an index, uses db.tablename.dropIndex(column). In below example, the index on column “username” is deleted or dropped.


点击(此处)折叠或打开

  1. > db.users.dropIndex({username:1})
  2. { "nIndexesWas" : 2, "ok" : 1 }
  3. > db.users.getIndexes()
  4. [
  5. {
  6. "v" : 1,
  7. "key" : {
  8. "_id" : 1
  9. },
  10. "ns" : "mydb.users",
  11. "name" : "_id_"
  12. }
  13. ]
  14. >

8.4 To create an unique index, uses db.tablename.ensureIndex({column},{unique:true}). In below example, an unique index is created on column “username”.


点击(此处)折叠或打开

  1. > db.users.ensureIndex({username:1},{unique:true});
  2. > db.users.getIndexes()
  3. [
  4. {
  5. "v" : 1,
  6. "key" : {
  7. "_id" : 1
  8. },
  9. "ns" : "mydb.users",
  10. "name" : "_id_"
  11. },
  12. {
  13. "v" : 1,
  14. "key" : {
  15. "username" : 1
  16. },
  17. "unique" : true,
  18. "ns" : "mydb.users",
  19. "name" : "username_1"
  20. }
  21. ]
  22. >

10. 帮助

At last, uses help() to guide you how to do things in MongoDB.

10.1 help – All available commands.


点击(此处)折叠或打开

  1. > help
  2. db.help() help on db methods
  3. db.mycoll.help() help on collection methods
  4. rs.help() help on replica set methods
  5. help admin administrative help
  6. help connect connecting to a db help
  7. help keys key shortcuts
  8. //...

10.2 db.help() – Shows help on db.


点击(此处)折叠或打开

  1. > db.help()
  2. DB methods:
  3. db.addUser(username, password[, readOnly=false])
  4. db.auth(username, password)
  5. db.cloneDatabase(fromhost)
  6. db.commandHelp(name) returns the help for the command
  7. db.copyDatabase(fromdb, todb, fromhost)
  8. db.createCollection(name, { size : ..., capped : ..., max : ... } )
  9. db.currentOp() displays the current operation in the db
  10. db.dropDatabase()
  11. db.eval(func, args) run code server-side
  12. db.getCollection(cname) same as db['cname'] or db.cname
  13. db.getCollectionNames()
  14. db.getLastError() - just returns the err msg string
  15. db.getLastErrorObj() - return full status object
  16. db.getMongo() get the server connection object
  17. db.getMongo().setSlaveOk() allow this connection to read from the nonmas
  18. ter member of a replica pair
  19. db.getName()
  20. db.getPrevError()
  21. db.getProfilingLevel() - deprecated
  22. db.getProfilingStatus() - returns if profiling is on and slow threshold
  23. db.getReplicationInfo()
  24. db.getSiblingDB(name) get the db at the same server as this one
  25. db.isMaster() check replica primary status
  26. db.killOp(opid) kills the current operation in the db
  27. db.listCommands() lists all the db commands
  28. db.logout()
  29. db.printCollectionStats()
  30. db.printReplicationInfo()
  31. db.printSlaveReplicationInfo()
  32. db.printShardingStatus()
  33. db.removeUser(username)
  34. db.repairDatabase()
  35. db.resetError()
  36. db.runCommand(cmdObj) run a database command. if cmdObj is a string, tu
  37. rns it into { cmdObj : 1 }
  38. db.serverStatus()
  39. db.setProfilingLevel(level,) 0=off 1=slow 2=all
  40. db.shutdownServer()
  41. db.stats()
  42. db.version() current version of the server
  43. db.getMongo().setSlaveOk() allow queries on a replication slave server
  44. db.fsyncLock() flush data to disk and lock server for backups
  45. db.fsyncUnock() unlocks server following a db.fsyncLock()
  46. >

10.3 db.collection.help() – Shows help on collection (table).


点击(此处)折叠或打开

  1. > db.users.help()
  2. DBCollection help
  3. db.users.find().help() - show DBCursor help
  4. db.users.count()
  5. db.users.dataSize()
  6. db.users.distinct( key ) - eg. db.users.distinct( 'x' )
  7. db.users.drop() drop the collection
  8. db.users.dropIndex(name)
  9. //...

10.4 db.collection.function.help() – Shows help on function.


点击(此处)折叠或打开

  1. > db.users.find().help()
  2. find() modifiers
  3. .sort( {...} )
  4. .limit( n )
  5. .skip( n )
  6. .count() - total # of objects matching query, ignores skip,limit
  7. .size() - total # of objects cursor would return, honors skip,limit
  8. .explain([verbose])
  9. //...

Done. Hope this summary of MongoDB commands could help others.

References

Official MongoDB tutorials
MongoDB Indexes

阅读(4300) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

vcdog2013-02-23 20:31:05

不错,学习了