使用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. 
3. mongod --help for help and startup options
4. 
5. Mon Dec 24 14:56:35
6. 
7. Mon Dec 24 14:56:35 warning: 32-bit servers don't have journaling enabled by def
8. 
9. ault. Please use --journal if you want durability.
10. 
11. Mon Dec 24 14:56:35
12. 
13. Mon Dec 24 14:56:35 [initandlisten] MongoDB starting : pid=1452 port=27017 dbpat
14. 
15. h=/data/db 32-bit host=chenzhengwei
16. 
17. Mon Dec 24 14:56:35 [initandlisten]
18. 
19. Mon Dec 24 14:56:35 [initandlisten] ** NOTE: when using MongoDB 32 bit, you are
20. 
21. limited to about 2 gigabytes of data
22. 
23. Mon Dec 24 14:56:35 [initandlisten] ** see http://blog.mongodb.org/post/13
24. 
25. 7788967/32-bit-limitations
26. 
27. Mon Dec 24 14:56:35 [initandlisten] ** with --journal, the limit is lower
28. 
29. Mon Dec 24 14:56:35 [initandlisten]
30. 
31. Mon Dec 24 14:56:35 [initandlisten] db version v2.0.8, pdfile version 4.5
32. 
33. Mon Dec 24 14:56:35 [initandlisten] git version: a340a57af7cdda865da420704e1d1b2
34. 
35. fac0cedc2
36. 
37. Mon Dec 24 14:56:35 [initandlisten] build info: windows sys.getwindowsversion(ma
38. 
39. jor=6, minor=0, build=6002, platform=2, service_pack='Service Pack 2') BOOST_LIB
40. 
41. _VERSION=1_42
42. 
43. Mon Dec 24 14:56:35 [initandlisten] options: {}
44. 
45. Mon Dec 24 14:56:35 [initandlisten] exception in initAndListen: 10296 dbpath (/d
46. 
47. ata/db) does not exist, terminating
48. 
49. Mon Dec 24 14:56:35 dbexit:
50. 
51. Mon Dec 24 14:56:35 [initandlisten] shutdown: going to close listening sockets..
52. 
53. .
54. 
55. Mon Dec 24 14:56:35 [initandlisten] shutdown: going to flush diaglog...
56. 
57. Mon Dec 24 14:56:35 [initandlisten] shutdown: going to close sockets...
58. 
59. Mon Dec 24 14:56:35 [initandlisten] shutdown: waiting for fs preallocator...
60. 
61. Mon Dec 24 14:56:35 [initandlisten] shutdown: closing all files...
62. 
63. Mon Dec 24 14:56:35 [initandlisten] closeAllFiles() finished
64. 
65. 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. 
3. 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. 
3. .0.8\data
4. 
5. Mon Dec 24 15:17:03
6. 
7. Mon Dec 24 15:17:03 warning: 32-bit servers don't have journaling enabled by def
8. 
9. ault. Please use --journal if you want durability.
10. 
11. Mon Dec 24 15:17:03
12. 
13. Mon Dec 24 15:17:03 [initandlisten] MongoDB starting : pid=5884 port=27017 dbpat
14. 
15. h=D:\J2ee\mongodb-win32-i386-2.0.8\data 32-bit host=chenzhengwei
16. 
17. Mon Dec 24 15:17:03 [initandlisten]
18. 
19. Mon Dec 24 15:17:03 [initandlisten] ** NOTE: when using MongoDB 32 bit, you are
20. 
21. limited to about 2 gigabytes of data
22. 
23. Mon Dec 24 15:17:03 [initandlisten] ** see http://blog.mongodb.org/post/13
24. 
25. 7788967/32-bit-limitations
26. 
27. Mon Dec 24 15:17:03 [initandlisten] ** with --journal, the limit is lower
28. 
29. Mon Dec 24 15:17:03 [initandlisten]
30. 
31. Mon Dec 24 15:17:03 [initandlisten] db version v2.0.8, pdfile version 4.5
32. 
33. Mon Dec 24 15:17:03 [initandlisten] git version: a340a57af7cdda865da420704e1d1b2
34. 
35. fac0cedc2
36. 
37. Mon Dec 24 15:17:03 [initandlisten] build info: windows sys.getwindowsversion(ma
38. 
39. jor=6, minor=0, build=6002, platform=2, service_pack='Service Pack 2') BOOST_LIB
40. 
41. _VERSION=1_42
42. 
43. Mon Dec 24 15:17:03 [initandlisten] options: { dbpath: "D:\J2ee\mongodb-win32-i3
44. 
45. 86-2.0.8\data" }
46. 
47. Mon Dec 24 15:17:03 [initandlisten] waiting for connections on port 27017
48. 
49. Mon Dec 24 15:17:03 [websvr] admin web console waiting for connections on port 2
50. 
51. 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. 
24. db.getReplicationInfo()
25. db.getSiblingDB(name) get the db at the same server as this one
26. db.isMaster() check replica primary status
27. db.killOp(opid) kills the current operation in the db
28. db.listCommands() lists all the db commands
29. db.logout()
30. db.printCollectionStats()
31. db.printReplicationInfo()
32. db.printSlaveReplicationInfo()
33. db.printShardingStatus()
34. db.removeUser(username)
35. db.repairDatabase()
36. db.resetError()
37. db.runCommand(cmdObj) run a database command. if cmdObj is a string, tu
38. rns it into { cmdObj : 1 }
39. db.serverStatus()
40. db.setProfilingLevel(level,) 0=off 1=slow 2=all
41. db.shutdownServer()
42. db.stats()
43. db.version() current version of the server
44. db.getMongo().setSlaveOk() allow queries on a replication slave server
45. db.fsyncLock() flush data to disk and lock server for backups
46. db.fsyncUnock() unlocks server following a db.fsyncLock()
47. >

 

 

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

http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/