mongo 数据库的简单使用
1.拉取mongo docker镜像及运行容器
sudo docker search mongo
sudo docker pull mongo:latest
sudo docker run -itd --name mongo -p 27017:27017 mongo --auth
2.添加admin ,及root 账户
sudo docker exec -it mongo mongo admin
db.createUser({ user:'admin',pwd:'123456',roles:[ { role:'userAdminAnyDatabase', db: 'admin'},"readWriteAnyDatabase"]});
db.auth('admin', '123456')
db.createUser({ user:'root',pwd:'123456',roles:[ { role:'root'}]});
db.auth('root', '123456')
sudo docker exec -it mongo mongo -u root -p 123456
3.mongoDB 与SQL
SQL术语/概念 | MongoDB术语/概念 | 解释/说明 |
---|
database | database | 数据库 |
table | collection | 数据库表/集合 |
row | document | 数据记录行/文档 |
column | field | 数据字段/域 |
index | index | 索引 |
table joins | | 表连接,MongoDB不支持 |
primary key | primary key | 主键,MongoDB自动将_id字段设置为主键 |
4.mongodb 的基础增删改
use runoob
show dbs
db.dropDatabase()
db.createCollection("mycol", { capped : true, autoIndexId : true, size : 6142800, max : 10000 } )
show collections
db.mycol.drop()
db.mycol.insertOne(<document>,{ writeConcern: <document> })
db.mycol.insertMany([ <document 1> , <document 2>, ... ], { writeConcern: <document>, ordered: <boolean> })
db.mycol.update({'title':'MongoDB-old'},{$set:{'title':'MongoDB-new'}},{multi:true})
db.mycol.save({
"_id" : ObjectId("56064f89ade2f21f36b03136"),
"title" : "MongoDB",
"description" : "MongoDB 是一个 Nosql 数据库",
"by" : "Runoob",
"url" : "http://www.runoob.com",
"tags" : [
"mongodb",
"NoSQL"
],
"likes" : 110
})
db.mycol.remove({'title':'MongoDB-new'})
db.mycol.find(query, projection)
db.mycol.find({likes : {$gt : 100}})
db.mycol.find({"title" : {$type : 'string'}})
db.mycol.find({},{"title":1,_id:0}).limit(2)
db.mycol.find({},{"title":1,_id:0}).limit(1).skip(1)
db.mycol.find({},{"title":1,_id:0}).sort({"likes":-1})
5.pymongo 在python 代码中的使用
from urllib import parse
from pymongo import MongoClient
host = '159.75.xxx.xxx'
username = 'root'
password = '123456'
passwd = parse.quote(password)
port = '27017'
mongo_url = 'mongodb://{0}:{1}@{2}:{3}'.format(username, passwd, host, port)
myclient = MongoClient(mongo_url)
def createdb(dbname):
return myclient[dbname]
def createTable(db, tablename):
return db[tablename]
def insetData():
mydict = { "name": "RUNOOB", "alexa": "10000", "url": "https://www.runoob.com" }
mydict2 = { "name": "RUNOOBdd", "alexa": "10000", "url": "https://www.runoob.com" }
db = createdb("dbcreate")
tablepy = createTable(db, 'newtable')
tablepy.insert_many([mydict,mydict2])
print(tablepy.find_one({"name": "RUNOOBdd"}))
def updateTable():
db = createdb("dbcreate")
tablepy = createTable(db, 'newtable')
tablepy.update_one({ "name": "RUNOOB"}, {"$set": { "name": "updateRUNOOB"}})
def delcollect():
db = createdb("dbcreate")
tablepy = createTable(db, 'newtable')
tablepy.delete_one({ "name": "updateRUNOOB"})
def findData():
db = createdb("dbcreate")
tablepy = createTable(db, 'newtable')
tablepy.find().sort("alexa", 1)
print(tablepy.find_one())
if __name__ == "__main__":
findData()
6.nodejs 调用mongo
npm install mongodb
demo
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://root:123456@159.75.118.xxx:27017';
// Database Name
const dbName = 'dbcreate';
// Create a new MongoClient
const op = {
useNewUrlParser: true
}
const client = new MongoClient(url, op);
const finddata = async()=> {
await client.connect();
const db = client.db(dbName);
const res = await db.collection('newtable').find().toArray();
console.log(res);
client.close()
}
finddata()
node xxxx.js