MongoDB 的基本操作指南。
命令行连接 MongoDB
连接 MongoDB
1
mongo localhost:27017/test -u mongo -p mongo
查看数据库
1
show dbs;
新建数据库
1
use mongo;
新建表
1
2
db.createCollection("mongo_test")
show collections
插入数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
db.mongo_test.insert({
id : 1,
name : "test",
age : 18,
description: "I'm a boy",
tags: ['basketball', 'football', 'programing']
})
db.mongo_test.insert({
id : 1,
name : "test",
age : 18,
description: "I'm a boy",
tags: ['basketball', 'football', 'programing'],
more : "new property"
})
查询数据
1
2
3
db.mongo_test.find().toArray()
db.mongo_test.find({id:1}).toArray()
db.mongo_test.find({},{id:1}).pretty()
删除数据
1
2
db.mongo_test.remove({})
db.mongo_test.remove({id:1})
删除表
1
db.mongo_test.drop()
其它操作
1
db.stats()
用户管理
新建用户
1
2
3
4
5
6
7
8
use mongo_test;
db.createUser(
{
user: "test",
pwd: "test",
roles: [ { role: "userAdminAnyDatabase", db: "mongo_test" } ]
}
);
查看用户
1
db.system.users.find().pretty()
查看角色
1
show roles;
删库跑路
1
2
use test
db.dropDatabase()
pymongo 连接 MongoDB
用 python 链接 MongoDB 的驱动,这篇文章介绍的不错。
安装 pymongo
1
pip install pymongo
使用 pymongo 连接 MongoDB
1
2
3
4
5
6
import pymongo
mongo_client = pymongo.MongoClient('localhost', 27017)
mongo_db = mongo_client.mongo_test
mongo_db.authenticate("mongo", "mongo")
collection = mongo_db.mongo_test
使用 pymongo 创建表
1
使用 pymongo 插入数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
collection.insert_one({
"id" : 1,
"name" : "test",
"age" : 18,
"description": "I'm a boy",
"tags": ['basketball', 'football', 'programing']
})
collection.insert_one({
"id" : 1,
"name" : "test",
"age" : 18,
"description": "I'm a boy",
"tags": ['basketball', 'football', 'programing'],
"more" : "new property"
})
使用 pymongo 查询数据
1
2
collection.find({"id":1})
collection.find({}, {"id":1})
使用 pymongo 删除数据
1
2
collection.remove({})
collection.remove({"id":1})
使用 pymongo 删除表
1
collection.dtop()