python 使用mongodb是通过pymongo进行操作的
安装:
pip install pymongo
连接
client = MongoClient('mongodb://localhost:27017/')
创建db或连接db
client.test_database
client['test-database']
db = client.get_database("db_name")
认证:
db.authenticate('username', 'password')
创建集合collection 或获取集合
db.test_collection
db['test-collection']
查看集合
db.list_collection_names()
新增
init_data = {"author": "tom", "text": "My first blog post!",
"tags": ["mongodb", "python", "pymongo"],
"date": datetime.datetime.utcnow()}
post_id = collection.insert_one(init_data).inserted_id
print post_id
查询单文档
可以根据条件进行查询, 也可以使用projectid进行查询,注意: project不是简单的str字符串
print collection.find_one({"_id": post_id})
print collection.find_one({"author": "Mike"})
使用projectid查询
from bson.objectid import ObjectId
def get(post_id):
# Convert from string to ObjectId:
document = client.db.collection.find_one({'_id':ObjectId(post_id)})
print collection.find_one({"_id": ObjectId("xkkwow1919")})
批量插入:
muilt_data = [{"author": "Mike",
"text": "Another post!",
"tags": ["bulk", "insert"],
"date": datetime.datetime(2009, 11, 12, 11, 14)},
{"author": "Eliot",
"title": "MongoDB is fun",
"text": "and pretty easy too!",
"date": datetime.datetime(2009, 11, 10, 10, 45)}]
result = collection.insert_many(muilt_data)
print result.inserted_ids
查询多个文档
collection_data = collect