我爱编程

MongoDB入门

2016-06-30  本文已影响137人  进击的前端

前言

NoSQL 非关系数据库。
MongoDB is an open-source, document database designed for ease of development and scaling.
MongoDB是开源的文档数据库。文档也就是关系数据库里面的一个Record,而文档的组织形式是collection.
网上找了一些资料都太旧了,还是直接英文文档最快。 首先官网文档镇楼,开头查了一些中文的MongoDB的资料之类的,发现其实官方文档最好。

首先介绍一下document,感觉就是Json格式的数据。这里介绍了一下如何导入数据。

{
  "address": {
     "building": "1007",
     "coord": [ -73.856077, 40.848447 ],
     "street": "Morris Park Ave",
     "zipcode": "10462"
  },
  "borough": "Bronx",
  "cuisine": "Bakery",
  "grades": [
     { "date": { "$date": 1393804800000 }, "grade": "A", "score": 2 },
     { "date": { "$date": 1378857600000 }, "grade": "A", "score": 6 },
     { "date": { "$date": 1358985600000 }, "grade": "A", "score": 10 },
     { "date": { "$date": 1322006400000 }, "grade": "A", "score": 9 },
     { "date": { "$date": 1299715200000 }, "grade": "B", "score": 14 }
  ],
  "name": "Morris Park Bake Shop",
  "restaurant_id": "30075445"
}

records(documents),collections,databases


一个数据就是一个record,然后records由collections组织,然后collections组成了database.

关于安装

  1. 首先下载MongoDB,下载地址,我的是windows系统,其实蛮简单的,下载,然后安装,因为现在有msi的文件了。

  2. 然后安装省略...

  3. 然后我们打开安装后的文件,有bin目录,介绍一下这些exe们


    bin目录下

亲爱的README给了介绍吧

COMPONENTS

bin/mongod - The database process.
bin/mongos - Sharding controller.
bin/mongo - The database shell (uses interactive javascript).

UTILITIES

bin/mongodump - MongoDB dump tool - for backups, snapshots, etc..
bin/mongorestore - MongoDB restore a dump
bin/mongoexport - Export a single collection to test (JSON, CSV)
bin/mongoimport - Import from JSON or CSV
bin/mongofiles - Utility for putting and getting files from MongoDB GridFS
bin/mongostat - Show performance statistics

开启数据库

数据库我们当然要存数据了,首先要指定数据的存储目录,当然我们要选个大一点的硬盘啦。
使用以下指令,这里默认安装在C盘 d:\test\mongodb\data这个目录指代数据库数据的目录。
C:\mongodb\bin\mongod.exe --dbpath d:\test\mongodb\data
如果你的目录有空格,那么目录就要双引了。
C:\mongodb\bin\mongod.exe --dbpath "d:\test\mongo db data"
出现如图所示界面,那就说明你成功地开启了数据库

数据库开启

python作为客户端操作数据库

这里介绍了怎么连接数据库的知识。

  1. 安装 pymongo
pip install pymongo
  1. 导入pymongo模块
from pymongo import MongoClient
  1. 创建连接,还有更详细的配置。
client = MongoClient()
  1. 使用数据库
db = client.primer
# 或者
db = client['primer']
  1. 使用Collection
coll = db.dataset
coll = db['dataset']
  1. 插入document
coll.insert_one({"key":"value"})

可以插入数组

>>> db.test.count()
0
>>> result = db.test.insert_many([{'x': i} for i in range(2)])
>>> result.inserted_ids
[ObjectId('54f113fffba522406c9cc20e'), ObjectId('54f113fffba522406c9cc20f')]
>>> db.test.count()
2
  1. 查找数据
cursor = coll.find()
for document in cursor:
    print document
查找结果

如果只是想看一下数据类型

print coll.find_one()

如果查找feild为特定的value的

cursor = db.restaurants.find({"address.zipcode": "10075"})
  1. 有条件地查找数据
    我们之前说的数据是类似键值对的组合,
{ <field1>: <value1>, <field2>: <value2>, ... }

然后我们想要 查找键为"borough"的值为"Manhattan"的文档数据.

cursor = db.restaurants.find({"borough": "Manhattan"})
cursor = db.restaurants.find({"address.zipcode": "10075"})

Greater Than 和Less Than

cursor = db.restaurants.find({"grades.score": {"$gt": 30}})
cursor = db.restaurants.find({"grades.score": {"$lt": 10}})

同时满足And

cursor = db.restaurants.find({"cuisine": "Italian", "address.zipcode": "10075"})

Or

cursor = db.restaurants.find( 
    {"$or": [{"cuisine": "Italian"}, {"address.zipcode": "10075"}]})
  1. 更新数据
    下面的代码,查找第一个文档有键值对 {"name": "Juni"}的,然后$set用来更新cuisine的值以及 $currentDate来更新lastModified的值。如果要更新的键值对不存在,那么会创造新的键值对。
result = db.restaurants.update_one(
    {"name": "Juni"},
    {
        "$set": {
            "cuisine": "American (New)"
        },
        "$currentDate": {"lastModified": True}
    }
)
  1. 删除数据
    python
    删除符合条件的document
result = db.restaurants.delete_many({"borough": "Manhattan"})
result.deleted_count

删除全部documents

result = db.restaurants.delete_many({})
result.deleted_count

删除 collection

db.restaurants.drop()
  1. 索引
    格式
[ ( <field1>: <type1> ), ... ]

单领域索引

import pymongo
db.restaurants.create_index([("cuisine", pymongo.ASCENDING)])

混合索引

import pymongo
db.restaurants.create_index([
    ("cuisine", pymongo.ASCENDING),
    ("address.zipcode", pymongo.DESCENDING)
])
上一篇下一篇

猜你喜欢

热点阅读