最近在写一个爬虫,使用的是MongoDB数据库,总结和简单记录下使用的方法。

  • MongoDB 是一个基于分布式文件存储的数据库。
  • 由 C++ 语言编写。
  • 旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。
  • MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。

1.创建、查看、删除数据库

使用use来创建(当数据库不存在),若存在就选择该库

1
2
3
4
5
> use xiwind
switched to db xiwind
> db
xiwind
>

如果你想查看所有数据库,可以使用 show dbs 命令:

1
2
3
4
> show dbs
local 0.078GB
test 0.078GB
>

删除了数据库 xiwind

1
2
3
4
> use xiwind
switched to db xiwind
> db.dropDatabase()
{ "dropped" : "xiwind", "ok" : 1 }

2.创建、查询、删除集合

在 test 数据库中创建 col 集合

1
2
3
4
> use test
switched to db test
> db.createCollection("col")
{ "ok" : 1 }

查看已有集合,可以使用 show collections 命令

1
2
3
> show collections
col
system.indexes

删除集合col

1
2
>db.col.drop()
true

3.文档插入、删除、更新、查询操作

在col集合中插入文档

1
2
3
4
5
6
> db.col.insert({title: 'MongoDB',
description: 'MongoDB 是一个 Nosql 数据库',
url: 'http://xiwind.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
})

在col集合中查询文档

  • find()查询所有,可以加条件
  • find_one()只返回一个结果
  • pretty()以易读的方式来读取数据
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    > db.col.find()
    { "_id" : ObjectId("56064886ade2f21f36b03134"), "title" : "MongoDB", "description" : "MongoDB 是一个 Nosql 数据库", "url" : "http://xiwind.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
    > db.col.find().pretty()
    {
    "_id" : ObjectId("56063f17ade2f21f36b03133"),
    "title" : "MongoDB",
    "description" : "MongoDB 是一个 Nosql 数据库",
    "url" : "http://xiwind.com",
    "tags" : [
    "mongodb",
    "database",
    "NoSQL"
    ],
    "likes" : 100
    }

条件查询表达式:

操作 格式 范例
等于 {key:value} db.col.find({“title” : “MongoDB”}).pretty()
小于 {key:{$lt:value}} db.col.find({“likes”:{$lt:50}}).pretty()
小于或等于 {<key>:{$lte:<value>}} db.col.find({“likes”:{$lte:50}}).pretty()
大于 {key:{$gt:value}} db.col.find({“likes”:{$gt:50}}).pretty()
大于或等于 {key:{$gte:value}} db.col.find({“likes”:{$gte:50}}).pretty()
不等于 {key:{$ne:value}} db.col.find({“likes”:{$ne:50}}).pretty()
{key1:value1, key2:value2} db.col.find({“title”:”MongoDB”,”likes”:100}).pretty
{$or:[{key1: value1}, {key2:value2}]} db.col.find(\$or:[{“title”:”MongoDB”, “likes”:100}]).pretty
正则 {key:{$regex:regex}} db.col.find({“title”:{\$regex:”^M.*”}}).pretty

在col集合中更新文档

更新指定文档内容:

1
> db.col.update({'title':'MongoDB'},{$set:{'title':'MongoDB 教程'}})

传入的文档替换已有文档:

1
2
3
4
5
6
7
8
9
10
11
>db.col.save({
"_id" : ObjectId("56064f89ade2f21f36b03136"),
"title" : "MongoDB",
"description" : "MongoDB 是一个 Nosql 数据库",
"url" : "http://xiwind.com",
"tags" : [
"mongodb",
"NoSQL"
],
"likes" : 110
})

在col集合中删除文档

1
2
>db.col.remove({'title':'MongoDB 教程'})
WriteResult({ "nRemoved" : 2 }) # 删除了两条数据

pymongo 模块的使用

连接mongodb的数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pymongo
import sys
import traceback
MONGODB_CONFIG = {
'host': '127.0.0.1',
'port': 27017,
'db_name': 'dbs',
'username': None,
'password': None
}
class MongoConn(object):
def __init__(self):
# connect db
try:
self.conn = pymongo.MongoClient(MONGODB_CONFIG['host'], MONGODB_CONFIG['port'])
self.db = self.conn[MONGODB_CONFIG['db_name']] # connect db
self.username=MONGODB_CONFIG['username']
self.password=MONGODB_CONFIG['password']
if self.username and self.password:
self.connected = self.db.authenticate(self.username, self.password)
else:
self.connected = True
except Exception:
print traceback.format_exc()
print 'Connect Statics Database Fail.'
sys.exit(1)

两种指定集合方式

1
2
3
conn = MongoConn()
collection = conn.db[test]
collection2 = conn.db.test

插入数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
student1 = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}
student2 = {
'id': '20170202',
'name': 'Mike',
'age': 21,
'gender': 'male'
}
# 插入一条数据
result = collection.insert_one(student1)
# 插入多条数据
result = collection.insert_many([student1, student2])

查询数据

1
2
3
4
result = collection.find_one({'name': 'Mike'})
# 指定范围,年龄大于20
results = collection.find({'age': {'$gt': 20}})
符号 含义 范例 示例含义
$regex 匹配正则 {‘name’: {‘$regex’: ‘^M.*’}} name以M开头
$exists 属性是否存在 {‘name’: {‘$exists’: True}} name属性存在
$type 类型判断 {‘age’: {‘$type’: ‘int’}} age的类型为int
$mod 数字模操作 {‘age’: {‘$mod’: [5, 0]}} 年龄模5余0
$text 文本查询 {‘$text’: {‘$search’: ‘Mike’}} text类型的属性中包含Mike字符串
$where 高级条件查询 {‘$where’: ‘obj.fans_count == obj.follows_count’} 自身粉丝数等于关注数

计数

1
2
# 统计查询结果有多少条数据
count = collection.find().count()

排序

1
2
3
# DESCENDING -- 降序
# ASCENDING -- 升序
results = collection.find().sort('age', pymongo.ASCENDING)

偏移

1
2
3
4
5
# skip() 忽略前几个放回结果,取后面
results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
# limit() 截取前几个返回结果
results = collection.find().sort('name', pymongo.ASCENDING).limit(2)

更新

1
2
3
4
5
# update_one 更新一条数据,update_many 更新多条数据
condition = {'name': 'Kevin'}
student = collection.find_one(condition)
student['age'] = 26
result = collection.update_one(condition, {'$set': student})

删除

1
result = collection.remove({'name': 'Kevin'})