1. 插入数据
参考链接 - runoob.com - Python Mongodb 插入文档
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["runoobdb"]
dblist = myclient.list_database_names()
mycol = mydb["sites"]
collist = mydb. list_collection_names()
mylist = [
{ "name": "Taobao", "alexa": "100", "url": "https://www.taobao.com" },
{ "name": "QQ", "alexa": "101", "url": "https://www.qq.com" },
{ "name": "Facebook", "alexa": "10", "url": "https://www.facebook.com" },
{ "name": "知乎", "alexa": "103", "url": "https://www.zhihu.com" },
{ "name": "Github", "alexa": "109", "url": "https://www.github.com" }
]
x = mycol.insert_many(mylist)
print(x.inserted_ids)
mycol2 = mydb['site2']
mylist2 = [
{ "_id": 1, "name": "RUNOOB", "cn_name": "菜鸟教程"},
{ "_id": 2, "name": "Google", "address": "Google 搜索"},
{ "_id": 3, "name": "Facebook", "address": "脸书"},
{ "_id": 4, "name": "Taobao", "address": "淘宝"},
{ "_id": 5, "name": "Zhihu", "address": "知乎"}
]
x2 = mycol2.insert_many(mylist2)
print(x2.inserted_ids)
2. 查询数据
参考链接 - runoob.com - Python Mongodb 查询文档
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["runoobdb"]
dblist = myclient.list_database_names()
mycol = mydb["sites"]
collist = mydb. list_collection_names()
myresult = mycol.find().limit(3)
for x in myresult:
print(x)
3. 修改数据
参考链接 - runoob.com - Python Mongodb 修改文档
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["runoobdb"]
dblist = myclient.list_database_names()
mycol = mydb["sites"]
4. 数据排序
参考链接 - runoob.com - Python Mongodb 数据排序
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["runoobdb"]
dblist = myclient.list_database_names()
mycol = mydb["sites"]
mydoc = mycol.find().sort("alexa", -1)
for x in mydoc:
print(x)
5. 数据删除
参考链接 - runoob.com - Python Mongodb 数据删除
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["runoobdb"]
dblist = myclient.list_database_names()
mycol = mydb["sites"]
mycol.drop()
6. 远程连接-索引查询
参考链接 - pymongo 建检索 - 针对大容量数据 ?? ??
import pymongo
import pandas as pd
import datetime
mongo_client = pymongo.MongoClient('mongodb://username:password@hostname/dbname:端口号')
col = mongo_client["数据库名"]["集合名"]
test_data = col.find().sort('_id', -1).limit(1)
test_data_2 = list(col.find({"$and" : [{'index1':'xxx'}, {'index2':'xxx'}]}).sort('_id', -1).limit(30))
start_time = "2022-1-1 10:00:00"
start_time = datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
end_time = "2022-1-1 10:00:00"
end_time = datetime.datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")
test_data3 = list(col.find({"$and": [{'index1':'xxx'},{'index2':'xxx'}, {'datetime':{'$gte': start_time, '$lte': end_time }}]}))
data_df = pd.DataFrame()
for i in test_data3:
data_df = data_df.append(i, ignore_index=True)
|