|
基本操作命令:
show dbs 查看所有数据库列表
use 连接指定的数据库
db 查看当前使用的数据库
> use testdb # 创建testdb数据库
switched to db testdb
> show dbs
admin 0.078GB
ceilometer 1.953GB
local 6.075GB
列出的数据库中没有testdb或者显示testdb(empty),是因为testdb里面没有任何东西。
> use testdb # 删除testdb数据库
switched to db testdb
> db.dropDatabase()
{ "dropped" : "testdb", "ok" : 1 }
> use testdb # 创建集合
switched to db testdb
> db.createCollection('users')
{ "ok" : 1 }
> show collections
system.indexes
users
> show collections # 删除集合
system.indexes
users
> db.users.drop()
true
> show collections
system.indexes
> db.createCollection('users') # 往集合中插入数据,如果集合没有会自动创建
{ "ok" : 1 }
> show collections
system.indexes
users
> db.users.insert([
... { name : 'yao',
... email : 'yao@qq.com'
... },
... { name: 'shen',
... email : 'shen@qq.com'
... }
... ])
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
> db.users.save([ # save也能实现上述insert的功能
... { name : 'test',
... email : 'test@qq.com'
... }
... ])
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 1,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
> user1=({'name': 'yao2','email': 'yao2@qq.com'}) # 插入文档,当然也可以把文档内容直接作为函数参数来替代document
{ "name" : "yao2", "email" : "yao2@qq.com" }
> db.users.insert(user1)
WriteResult({ "nInserted" : 1 })
> db.users.update({"name":'yao2'},{$set:{'email':'yaotest@qq.com'}}) # 更新文档,需要引入关键字$set
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.find({'name':'yao2'}).pretty()
{
"_id" : ObjectId("55e262dc957ba26c00b19e42"),
"name" : "yao2",
"email" : "yaotest@qq.com"
}
> db.users.save({"_id":ObjectId("55e2673b957ba26c00b19e45"),"name":'yao2','email':'yaotest2@qq.com'}) # 替换存在的文档,但是update更好用点。
> db.users.remove({'name':'yao2'}) # 删除文档
WriteResult({ "nRemoved" : 4 })
> db.users.find({'name':'yao2'}).pretty()
|
|
|