NoSQL: MongoDB快速上手

一、introduction

1. 基本概念

NoSQL: MongoDB快速上手_第1张图片

NoSQL: MongoDB快速上手_第2张图片

二、 相关操作

1. 基本操作

  1. 终端启动: start_mongo
  2. 查看版本:db.version()
  3. 查看数据库list: show dbs
  4. 创建database< training >: use training
  5. 创建collection: db.createCollection("mycollection")
  6. 查看创建好的collection:show collections
  7. 插入一条document:db.mycollection.insert({"color":"blue","example":"sky"})
  8. 查看documents数量:db.mycollection.count()
  9. 列出所有document:db.mycollection.find()
  10. 退出服务器: exit

2. create、read、update、delete

本部分采用的collection名字为languages

首先插入一些数据:

db.languages.insert({"name":"java","type":"object oriented"})
db.languages.insert({"name":"python","type":"general purpose"})
db.languages.insert({"name":"scala","type":"functional"})
db.languages.insert({"name":"c","type":"procedural"})
db.languages.insert({"name":"c++","type":"object oriented"})

read

  1. 列出第一条doc:db.languages.findOne()
  2. 列出所有doc:db.languages.find()
  3. 列出前三个doc:db.languages.find().limit(3)
  4. 列出对应标签的doc:db.languages.find({"name":"python"})
  5. 列出所有的doc,但是仅仅显示name:db.languages.find({},{"name":1})
  6. 列出所有doc,但是不显示name:db.languages.find({},{"name":0})
  7. 列出所有面向对象语言名字: db.languages.find({"type":"object oriented"},{"name":1})

update

通用语法:

db.collection.updateMany({what documents to find},{$set:{what fields to set}})

举例:

  1. 给所有doc多插入一块相同的内容:
    db.languages.updateMany({},{$set:{"description":"programming language"}})
  2. 为python对应的doc添加作者:
    db.languages.updateMany({"name":"python"},{$set:{"creator":"Guido van Rossum"}})

delete

  1. 删除对应名字的doc:db.languages.remove({"name":"scala"})
  2. 删除对应类型的doc:db.languages.remove({"type":"object oriented"})
  3. 删除全部docs:db.languages.remove({})

总结:
CRUD四种操作,基本模式使用{key:value}来进行筛选要改动的doc
其中update稍微复杂一点,需要先找到,然后再更改,改的部分,需要使用$set标识出来。

3. indexes

bigdata是学习本部分创建的Collection,通过如下循环创建了20万个doc:

use training
for (i=1;i<=200000;i++){print(i);db.bigdata.insert({"account_no":i,"balance":Math.round(Math.random()*1000000)})}
  1. 创建index: db.bigdata.createIndex({"account_no":1})
    {}中通常选取最常用的field
  2. 查询所有的indexes: db.bigdata.getIndexes()
  3. 删除index:db.bigdata.dropIndex({"account_no":1})

4. aggregation framework

marks是学习本部分创建的Collection,具体数据内容如下:

use training
db.marks.insert({"name":"Ramesh","subject":"maths","marks":87})
db.marks.insert({"name":"Ramesh","subject":"english","marks":59})
db.marks.insert({"name":"Ramesh","subject":"science","marks":77})
db.marks.insert({"name":"Rav","subject":"maths","marks":62})
db.marks.insert({"name":"Rav","subject":"english","marks":83})
db.marks.insert({"name":"Rav","subject":"science","marks":71})
db.marks.insert({"name":"Alison","subject":"maths","marks":84})
db.marks.insert({"name":"Alison","subject":"english","marks":82})
db.marks.insert({"name":"Alison","subject":"science","marks":86})
db.marks.insert({"name":"Steve","subject":"maths","marks":81})
db.marks.insert({"name":"Steve","subject":"english","marks":89})
db.marks.insert({"name":"Steve","subject":"science","marks":77})
db.marks.insert({"name":"Jan","subject":"english","marks":0,"reason":"absent"})
  1. limit 限制输出行数:
    db.marks.aggregate([{"$limit":2}])
    仅仅输出前两行的内容
  2. sort 基于column:
    db.marks.aggregate([{"$sort":{"marks":1}}])
    命令行按照mark分数升序输出,如果{"marks":-1}那么将会按照降序顺序输出。
  3. sort和limit配合,输出成绩最好或者最差的:
    db.marks.aggregate([ {"$sort":{"marks":-1}}, {"$limit":2} ])
    像pipeline一样,在[]中按照顺序排开,两种operator中用逗号隔开。
    注意: 每个operator都要上引号
  4. 输出各个学科的平均分数:
    group 经常和 sum,avg,min,max等配合使用
    db.marks.aggregate([
    {
        "$group":{
            "_id":"$subject",
            "average":{"$avg":"$marks"}
            }
    }
    ])
    
    上式与如下sql相同含义:
    select subject, avg(marks) from marks
    group by subject;
    
    group中的tag,_id不能改

最后,所有如上的操作,都可以像pipeline一样,在[]中按照逗号排开。

5. replication $ Sharding

redundancy
availibility
fault

sharding:

5. 使用python连接mongoDB

连接数据库

from pymongo import MongoClient
user = 'root'
password = 'MjQwOTgtcnNhbm5h'  # 改为自己的password
host='localhost'
#create the connection url
connecturl = "mongodb://{}:{}@{}:27017/?authSource=admin".format(user,password,host)


# connect to mongodb server
print("Connecting to mongodb server")
connection = MongoClient(connecturl)


# get database list
print("Getting list of databases")
dbs = connection.list_database_names()

# print the database names

for db in dbs:
    print(db)
print("Closing the connection to the mongodb server")


# close the server connecton
connection.close()

操作文件

在连接好数据库之后,可以与数据库交互:


connection = MongoClient(connecturl)


# select the 'training' database 

db = connection.training

# select the 'python' collection 

collection = db.python

# create a sample document

doc = {"lab":"Accessing mongodb using python", "Subject":"No SQL Databases"}

# insert a sample document

print("Inserting a document into collection.")
db.collection.insert(doc)

# query for all documents in 'training' database and 'python' collection

docs = db.collection.find()

print("Printing the documents in the collection.")

for document in docs:
    print(document)

你可能感兴趣的:(nosql,mongodb,nosql,数据库)