使用mongodb进行增删改查等基本操作。本例使用 mongodb-win32-i386-2.0.8 , 在windows xp下进行测试。 MongoDB客户端和服务端都运行在本地(同一台机器)。
1.安装MongoDB1.1.下载mongodb,并解压,本例安装在D:\J2ee\mongodb-win32-i386-2.0.8
1.2.使用mongod.exe启动mongodb
$MongoDB-folder/bin/mongod
- D:\J2ee\mongodb-win32-i386-2.0.8\bin>mongod
- mongod --help for help and startup options
- Mon Dec 24 14:56:35
- Mon Dec 24 14:56:35 warning: 32-bit servers don't have journaling enabled by def
- ault. Please use --journal if you want durability.
- Mon Dec 24 14:56:35
- Mon Dec 24 14:56:35 [initandlisten] MongoDB starting : pid=1452 port=27017 dbpat
- h=/data/db 32-bit host=chenzhengwei
- Mon Dec 24 14:56:35 [initandlisten]
- Mon Dec 24 14:56:35 [initandlisten] ** NOTE: when using MongoDB 32 bit, you are
- limited to about 2 gigabytes of data
- Mon Dec 24 14:56:35 [initandlisten] ** see http://blog.mongodb.org/post/13
- 7788967/32-bit-limitations
- Mon Dec 24 14:56:35 [initandlisten] ** with --journal, the limit is lower
- Mon Dec 24 14:56:35 [initandlisten]
- Mon Dec 24 14:56:35 [initandlisten] db version v2.0.8, pdfile version 4.5
- Mon Dec 24 14:56:35 [initandlisten] git version: a340a57af7cdda865da420704e1d1b2
- fac0cedc2
- Mon Dec 24 14:56:35 [initandlisten] build info: windows sys.getwindowsversion(ma
- jor=6, minor=0, build=6002, platform=2, service_pack='Service Pack 2') BOOST_LIB
- _VERSION=1_42
- Mon Dec 24 14:56:35 [initandlisten] options: {}
- Mon Dec 24 14:56:35 [initandlisten] exception in initAndListen: 10296 dbpath (/d
- ata/db) does not exist, terminating
- Mon Dec 24 14:56:35 dbexit:
- Mon Dec 24 14:56:35 [initandlisten] shutdown: going to close listening sockets..
- .
- Mon Dec 24 14:56:35 [initandlisten] shutdown: going to flush diaglog...
- Mon Dec 24 14:56:35 [initandlisten] shutdown: going to close sockets...
- Mon Dec 24 14:56:35 [initandlisten] shutdown: waiting for fs preallocator...
- Mon Dec 24 14:56:35 [initandlisten] shutdown: closing all files...
- Mon Dec 24 14:56:35 [initandlisten] closeAllFiles() finished
- Mon Dec 24 14:56:35 dbexit: really exiting now
以上并没有启动mongod,抛出了以下异常信息:
- Mon Dec 24 14:56:35 [initandlisten] exception in initAndListen: 10296 dbpath (/d
- ata/db) does not exist, terminating
即dbpath(/data/db)不存在
正确方法,创建目录D:\J2ee\mongodb-win32-i386-2.0.8\data,用于mongodb存放数据。
执行以下命令:
- D:\J2ee\mongodb-win32-i386-2.0.8\bin>mongod -dbpath D:\J2ee\mongodb-win32-i386-2
- .0.8\data
- Mon Dec 24 15:17:03
- Mon Dec 24 15:17:03 warning: 32-bit servers don't have journaling enabled by def
- ault. Please use --journal if you want durability.
- Mon Dec 24 15:17:03
- Mon Dec 24 15:17:03 [initandlisten] MongoDB starting : pid=5884 port=27017 dbpat
- h=D:\J2ee\mongodb-win32-i386-2.0.8\data 32-bit host=chenzhengwei
- Mon Dec 24 15:17:03 [initandlisten]
- Mon Dec 24 15:17:03 [initandlisten] ** NOTE: when using MongoDB 32 bit, you are
- limited to about 2 gigabytes of data
- Mon Dec 24 15:17:03 [initandlisten] ** see http://blog.mongodb.org/post/13
- 7788967/32-bit-limitations
- Mon Dec 24 15:17:03 [initandlisten] ** with --journal, the limit is lower
- Mon Dec 24 15:17:03 [initandlisten]
- Mon Dec 24 15:17:03 [initandlisten] db version v2.0.8, pdfile version 4.5
- Mon Dec 24 15:17:03 [initandlisten] git version: a340a57af7cdda865da420704e1d1b2
- fac0cedc2
- Mon Dec 24 15:17:03 [initandlisten] build info: windows sys.getwindowsversion(ma
- jor=6, minor=0, build=6002, platform=2, service_pack='Service Pack 2') BOOST_LIB
- _VERSION=1_42
- Mon Dec 24 15:17:03 [initandlisten] options: { dbpath: "D:\J2ee\mongodb-win32-i3
- 86-2.0.8\data" }
- Mon Dec 24 15:17:03 [initandlisten] waiting for connections on port 27017
- Mon Dec 24 15:17:03 [websvr] admin web console waiting for connections on port 2
- 8017
2. 连接MongoDB再打开一个命令行,执行以下mongo命令:
- D:\J2ee\mongodb-win32-i386-2.0.8\bin>mongo
- MongoDB shell version: 2.0.8
- connecting to: test
- >
3. 创建数据库和表
mongodb中使用以下命令,切换到某个数据库(即使它还不存在)
use database-name
mongodb中当你往一个表里面插入一条记录时,相应的表和数据库就被自动创建好了。具体看下面的例子:
- D:\J2ee\mongodb-win32-i386-2.0.8\bin>mongo
- MongoDB shell version: 2.0.8
- connecting to: test
- > use mydb
- switched to db mydb
- > db.users.insert({username:"henry",password:"123456"})
- > db.users.find()
- { "_id" : ObjectId("50d803393cc996b4e8ce22de"), "username" : "henry", "password"
- : "123456" }
- >
以下是三个常用的命令
- show dbs – List all databases.
- use db_name – Switches to db_name.
- show collections – List all tables in the current selected database.
- > show dbs
- local (empty)
- mydb 0.03125GB
- > use mydb
- switched to db mydb
- > show collections
- system.indexes
- users
- >
Note
In MongoDB, collection means table in SQL.
4. 插入一条记录插入记录的语法的两种方式:
- db.tablename.insert({data}) or db.tablename.save({data})
- > db.users.save({username:"google",password:"google123"})
- > db.users.find()
- { "_id" : ObjectId("50d803393cc996b4e8ce22de"), "username" : "henry", "password": "123456" }
- { "_id" : ObjectId("50d8046a3cc996b4e8ce22df"), "username" : "google", "password" : "google123" }
5. 更新记录更新一条记录语法:
db.tablename.update({criteria},{$set: {new value}}).
下面的例子中更新用户henry的密码:
- > db.users.update({username:"henry"},{$set:{password:"henry123456"}})
- > db.users.find()
- { "_id" : ObjectId("50d8046a3cc996b4e8ce22df"), "username" : "google", "password" : "google123" }
- { "_id" : ObjectId("50d803393cc996b4e8ce22de"), "password" : "henry123456", "username" : "henry" }
- >
6. 查询记录
查找记录的语法:
db.tablename.find({criteria}).
6.1 列出users表中的所有记录
- > db.users.find()
- { "_id" : ObjectId("50d8046a3cc996b4e8ce22df"), "username" : "google", "password" : "google123" }
- { "_id" : ObjectId("50d803393cc996b4e8ce22de"), "password" : "henry123456", "username" : "henry" }
- >
6.2 查询username 为henry的记录
- > db.users.find({username:"henry"})
- { "_id" : ObjectId("50d803393cc996b4e8ce22de"), "password" : "henry123456", "username" : "henry" }
7. 删除记录
删除记录的语法:
db.tablename.remove({criteria}).
下面的例子
- > db.users.remove({username:"google"})
- > db.users.find()
- { "_id" : ObjectId("50d803393cc996b4e8ce22de"), "password" : "henry123456", "username" : "henry" }
- >
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.
- > db.users.getIndexes()
- [
- {
- "v" : 1,
- "key" : {
- "_id" : 1
- },
- "ns" : "mydb.users",
- "name" : "_id_"
- }
- ]
- >
8.2 To create an index, uses db.tablename.ensureIndex(column). In below example, an index is created on column “username”.
- > db.users.ensureIndex({username:1})
- > db.users.getIndexes()
- [
- {
- "v" : 1,
- "key" : {
- "_id" : 1
- },
- "ns" : "mydb.users",
- "name" : "_id_"
- },
- {
- "v" : 1,
- "key" : {
- "username" : 1
- },
- "ns" : "mydb.users",
- "name" : "username_1"
- }
- ]
- >
8.3 To drop an index, uses db.tablename.dropIndex(column). In below example, the index on column “username” is deleted or dropped.
- > db.users.dropIndex({username:1})
- { "nIndexesWas" : 2, "ok" : 1 }
- > db.users.getIndexes()
- [
- {
- "v" : 1,
- "key" : {
- "_id" : 1
- },
- "ns" : "mydb.users",
- "name" : "_id_"
- }
- ]
- >
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”.
- > db.users.ensureIndex({username:1},{unique:true});
- > db.users.getIndexes()
- [
- {
- "v" : 1,
- "key" : {
- "_id" : 1
- },
- "ns" : "mydb.users",
- "name" : "_id_"
- },
- {
- "v" : 1,
- "key" : {
- "username" : 1
- },
- "unique" : true,
- "ns" : "mydb.users",
- "name" : "username_1"
- }
- ]
- >
10. 帮助
At last, uses help() to guide you how to do things in MongoDB.
10.1 help – All available commands.
- > help
- db.help() help on db methods
- db.mycoll.help() help on collection methods
- rs.help() help on replica set methods
- help admin administrative help
- help connect connecting to a db help
- help keys key shortcuts
- //...
10.2 db.help() – Shows help on db.
- > db.help()
- DB methods:
- db.addUser(username, password[, readOnly=false])
- 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 the current operation in the db
- db.dropDatabase()
- db.eval(func, args) run code server-side
- 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 this connection to read from the nonmas
- ter member of a replica pair
- 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.isMaster() check replica primary status
- db.killOp(opid) kills the current operation in the db
- db.listCommands() lists all the db commands
- db.logout()
- 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, tu
- rns it into { cmdObj : 1 }
- db.serverStatus()
- db.setProfilingLevel(level,) 0=off 1=slow 2=all
- db.shutdownServer()
- db.stats()
- db.version() current version of the server
- db.getMongo().setSlaveOk() allow queries on a replication slave server
- db.fsyncLock() flush data to disk and lock server for backups
- db.fsyncUnock() unlocks server following a db.fsyncLock()
- >
10.3 db.collection.help() – Shows help on collection (table).
- > db.users.help()
- DBCollection help
- db.users.find().help() - show DBCursor help
- db.users.count()
- db.users.dataSize()
- db.users.distinct( key ) - eg. db.users.distinct( 'x' )
- db.users.drop() drop the collection
- db.users.dropIndex(name)
- //...
10.4 db.collection.function.help() – Shows help on function.
- > db.users.find().help()
- find() modifiers
- .sort( {...} )
- .limit( n )
- .skip( n )
- .count() - total # of objects matching query, ignores skip,limit
- .size() - total # of objects cursor would return, honors skip,limit
- .explain([verbose])
- //...
Done. Hope this summary of MongoDB commands could help others.
References
Official MongoDB tutorials
MongoDB Indexes
阅读(4300) | 评论(1) | 转发(0) |