MongoDB是面向文档的NoSQL数据库用于大量数据存储
常用术语
- _id 必填的字段,表示MongoDB文档中的唯一值,类似于文档的主键
- 集合 分组,等效于在任何关系型数据库中创建的表
- 游标 是指向查询结果集的指针
- 数据库 表的容器,数据库在文件系统上都有文件集
- 文档 集合中的记录基本上称为文档
- 字段 文档具有零个或多个字段,类似于关系数据库中的列
- JSON 轻量级的数据交换格式。可读行高易于解析的纯文本格式用于表达结构化数据
远程访问
sudo vim /etc/mongod.conf
修改 bind_ip = 0.0.0.0
sudo service mongod restart
常用命令
创建数据库 use website
创建集合 db.website.insert({'url': 'www.python.org', 'tag': 'python'})
> s = [{'url': 'www.baidu.com', 'tag': 'baidu'}, {'url': 'www.github.com', 'tag': 'github'}, {'url': 'www.django.com', 'tag':'django'}]
[
{
"url" : "www.baidu.com",
"tag" : "baidu"
},
{
"url" : "www.github.com",
"tag" : "github"
},
{
"url" : "www.django.com",
"tag" : "django"
}
]
> db.website.insert(s)
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 3,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
以JSON格式打印
> db.website.find().forEach(printjson)
{
"_id" : ObjectId("5ecf315bf9e63c8097353c74"),
"url" : "www.python.org",
"tag" : "python"
}
{
"_id" : ObjectId("5ecf3209f9e63c8097353c75"),
"url" : "www.baidu.com",
"tag" : "baidu"
}
{
"_id" : ObjectId("5ecf3209f9e63c8097353c76"),
"url" : "www.github.com",
"tag" : "github"
}
{
"_id" : ObjectId("5ecf3209f9e63c8097353c77"),
"url" : "www.django.com",
"tag" : "django"
}
>
计数功能
db.website.count()
删除文件
db.website.remove({tag:'django'})
文档更新
db.website.update({"tag":"baidu"}, {$set: {"url": "www.360.com"}})
创建管理员用户
> db.createUser({user:'solomon', pwd: '147258', roles:[{role: "userAdminAnyDatabase", db:"admin"}]})
Successfully added user: {
"user" : "solomon",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}
为单个数据库创建用户
> db.createUser({user:'world', pwd: '147258', roles:[{role:"userAdmin",db:"website"}]})
Successfully added user: {
"user" : "world",
"roles" : [
{
"role" : "userAdmin",
"db" : "website"
}
]
}