python-mongodb

install pip:
sudo apt-get install python3-pip

upgrading pip:
pip install -U pip(on linux or macos)
python -m pip install -U pip(on windows)

install pymongo:
sudo pip install pymongo

sudo apt-get install mongodb

mkdir /data/db

start mongodb:./bin/mongod –dbpath=/data/db

start mongodb daemon:
mkdir /log
mongod –dbpath=/data/db/ –fork –logpath=/log/mongodb.log
or
mkdir /opt/mongodb/conf.d/mongodb.conf
vim /opt/mongodb/conf.d/mongodb.conf
and paste bellow:
port=27017
dbpath=/data/db
logpath=/log/mongodb.log
logappend=true
fork=true
mongod -c /opt/mongodb/conf.d/mongodb.conf

connect.py

import pymongo
from pymongo import *

get database connection

client = MongoClient()

the same way

client = MongoClient(“localhost”,27017)

client = MongoClient(“mongodb://localhost:27017/“)

assign database and collection to operat

db = client.test_db
collection = db.test_collection

IDUS

insert

mydict = {“name”: “cursor”, “sex”: “female”, “job”: “dev”}
collection.insert(mydict)
collection.insert_one(mydict)
mylist = []
mylist.append(mydict)

insert_many param must be list

collection.insert_many(mylist)

find

find_one() just show meet the conditions first collection

find() return all the object array which meet the conditions

collection.find({“name”: “cursor”})[0]
collection.find({“name”: “cursor”})[1]

use for-in operation to loop all

for i in collection.find({“name”: “cursor”}):
print(i)

search assign conditions

collection.find_one({“name”: “cursor”})
collection.find_one({“name”: “cursor”, “sex”: “female”})

use .count()

collection.find().count() # this is equal to collection.count()
collection.find({“name”: “cursor”}).count()

条件查询 $lt(<) $gt(>) $lte(<=) $gte(>=) #ne(!=)

collection.find({“age”: {“$lt”: 30}})

sort the find result

collection.find().sort(“age”) # defult ASC
collection.find().sort(“age”, pymongo.ASCENDING)
collection.find().sort(“age”, pymongo.DESCENDING)

查询 database中所有collection

db.collection_names()
db.collection_names(include_system_collections=False) # 不包括系统collection,一般指的是system.indexes

update

temp = collection.find_one({“name”: “Lucy”})
temp2 = temp.copy()
temp[“name”] = “Jordan”

如果此时temp[“_id”]在该collection中已经存在,则.save()为更新操作,与 .replace_one() 作用相同,否则 .save() 为插入操作,与 .insert_one() 作用相同。

collection.save(temp) # 或 .update() ,注意参数形式
collection.update(temp, temp2) # 将temp更新为temp2

还要注意的一点是,.replace_one()需要传入两个参数,分别为当前document和要更新为的 document ,与 .update() 相同

collection.replace_one(old_document, new_document)

delete

collection.remove(temp) # 即便该temp不存在也不会报错
collection.delete_one(temp)
collection.delete_many(temp) # 与 .insert_many() 不同,在temp不是list类型时也不会报错

JSON序列化与反序列化

import json

如果想序列化为标准 JSON 格式,两种方式,方式一,json 包中的 dumps:

for i in collection.find({“name”: “cursor”}):
del i[“_id”] # 不能直接转换,无法识别ObjectId
json.dumps(i)

bson.json_util包中封装的 dumps:

from bson import Binary, Code
from bson.json_util import dumps

dumps([{‘foo’: [1, 2]},
{‘bar’: {‘hello’: ‘world’}},
{‘code’: Code(“function x() { return1; }”)},
{‘bin’: Binary(“”)}])

‘[{“foo”: [1, 2]}, {“bar”: {“hello”:”world”}}, {“code”: {“$code”: “function x(){ return 1; }”, “$scope”: {}}}, {“bin”:{“$binary”: “”, “$type”: “00”}}]’

对应的反序列化方法为bson.json_util.loads()

    原文作者:Cursor_fei
    原文地址: https://www.jianshu.com/p/22ef74a2a498
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞