python操作Mongodb示例

使用python 简单操作mongodb数据库

下载python中mongodb包

pip install pymongo

示例

简单展示一下python如何连接mongodb数据库,删除数据, 添加数据, 以及查询数据

#coding=utf-8
from pymongo import MongoClient
import time

client = MongoClient('mongodb://192.168.1.94:27017/')
db = client.HumanAi                                        //选择HumanAi数据库
collection = db.human                                      //选择HumanAi下human表

item_count = collection.count()
# remove all item_info
remove_start_time = time.time()
collection.remove({})
remove_end_time = time.time()
remove_spend_time = (remove_end_time - remove_start_time)

sum = 10000000
# 时间戳 单位ms
timestamp = 1531380608000  
index = 1

insert_start_time = time.time()
while index <= sum:
    collection.insert({
        'absTimestamp' : timestamp,
        'rect_x' : 10,
        'rect_y' : 10,
        'rect_width' : 200,
        'rect_height' : 200,
        'name' : 'zw',
        'age': 20,
        'gender' : 'male',
        'channel_number' : 1,
        'gender_confidence' : 0.5,
        'feature_confidence' : 0.5,
        'match_confidence' : 0.5,
        'flag' : 0})

    index += 1
    timestamp += 1

insert_end_time = time.time()
insert_spend_time = (insert_end_time - insert_start_time)

findtimestamp = timestamp-3000
query_start_time = time.time()
search_result = collection.find({"absTimestamp": {"$lt" :timestamp, "$gt" : findtimestamp}})
print("查找到的数据长度:",search_result.count())
query_end_time = time.time()
query_spend_time = (query_end_time - query_start_time)

print("删除",item_count,"数据时间","{:.4f}".format(remove_spend_time))
print("添加",sum,"条数据时间","{:.4f}".format(insert_spend_time))
print("查找数据时间:","{:.4f}".format(query_spend_time))