$./mongod 启动Mongodb
$./mongo 连接Mongodb 默认是localhost
$./use 数据库名称 通知此会话将使用该数据库
$./show dbs 列出所有数据库
Mongodb不需要我们创建数据库或者集合.在你插入数据的时候会自动创建相关的数据库跟集合.
1) 创建
CREATE TABLE USERS (a Number, b Number)
(隐式,但也可以显式创建,例如一个封顶集合)
> # mongo shell
> db.createCollection(“mycoll”, {capped:true, size:100000})
> show collections
如果驱动支持,还可以
> db.runCommand( {createCollection:”mycoll”, capped:true, size:100000} )
(2) 插入
INSERT INTO USERS VALUES(1,1)
> db.users.insert({a:1,b:1})
(3) 查询
SELECT a,b FROM users
> db.users.find({}, {a:1,b:1})
SELECT * FROM users
> db.users.find()
SELECT * FROM users WHERE age=33
> db.users.find({age:33})
SELECT a,b FROM users WHERE age=33
> db.users.find({age:33}, {a:1,b:1})
SELECT * FROM users WHERE age=33 ORDER BY name
> db.users.find({age:33}).sort({name:1})
SELECT * FROM users WHERE age>33
> db.users.find({‘age’:{$gt:33}})
> db.users.find({age:{$gt:33}})
SELECT * FROM users WHERE age<33
> db.users.find({‘age’:{$lt:33}})
> db.users.find({age:{$lt:33}})
SELECT * FROM users WHERE a=1 and b=’q’
> db.users.find({a:1,b:’q'})
(4) 更新(20110311更新:包括删除?)
UPDATE users SET a=1 WHERE b=’q’
> db.users.update({b:’q'}, {$set:{a:1}}, false, true)
(5) 索引
CREATE INDEX myindexname ON users(name)
> db.users.ensureIndex({name:1})
EXPLAIN SELECT * FROM users WHERE z=3
> db.users.find({z:3}).explain()
(6) 集合函数,排序和分页和其它查询
SELECT * FROM users ORDER BY name DESC
> db.users.find().sort({name:-1})
SELECT * FROM users LIMIT 10 SKIP 20
> db.users.find().limit(10).skip(20)
SELECT * FROM users LIMIT 1
> db.users.findOne()
SELECT DISTINCT last_name FROM users
> db.users.distinct(‘last_name’)
SELECT COUNT(*y) FROM users
> db.users.count()
SELECT COUNT(*y) FROM users where AGE > 30
> db.users.find({age: {‘$gt’: 30}}).count()
SELECT COUNT(AGE) from users
> db.users.find({age: {‘$exists’: true}}).count()
更详细的用法见手册
http://www.mongodb.org/display/DOCS/Manual