我想插入我的查詢對象在pymongo連接器創建大熊貓數據幀:格式MongoDB的查詢中使用Pymongo
import pandas as pd
from pymongo import MongoClient
def _connect_mongo(host, port, username, password, db):
if username and password:
mongo_uri = 'mongodb://%s:%[email protected]%s:%s/%s' % (username, password, host, port, db)
conn = MongoClient(mongo_uri)
else:
conn = MongoClient(host, port)
return conn[db]
def read_mongo(db, collection, query={}, host='localhost', port=27017, username=None, password=None, no_id=True):
""" Read from Mongo and Store into DataFrame """
# Connect to MongoDB
db = _connect_mongo(host=host, port=port, username=username, password=password, db=db)
# Make a query to the specific DB and Collection
cursor = db[collection].find(query)
# Expand the cursor and construct the DataFrame
df = pd.DataFrame(list(cursor))
# Delete the _id
# if no_id:
# del df['_id']
return df
我的查詢被定義爲:
query_1 = "{
"status" : {"$ne" : "deprecated"},
"geoLocationData.date" : { $gte : new ISODate("2016-08-03") }
},
{ "geoLocationData.date": 1,
"geoLocationData.iso": 1,
"httpRequestData.ipAddress": 1,
"geoLocationData.city": 1,
"geoLocationData.latitude": 1,
"geoLocationData.longitude": 1 }"
將其插入 - 獲得一個數據幀大熊貓:
df = read_mongo(db, collection, query_1, host, port, username, password)
我得到的錯誤:
TypeError: filter must be an instance of dict, bson.son.SON, or other type that inherits from collections.Mapping
如果我只是省略子文檔,查詢工作得很好,我可以將其轉換爲數據框。
我想這是關於將我的查詢轉換成字典(與子文件)。 我該怎麼做?
你是否按照'query_1 =「db.finger ......})」'的含義給查詢提供了一個字符串? –
對不起,我編輯過。我正在定義查詢省略查找語句@SteveRossiter – xxxvinxxx