我用以下方式使用pymongo:
from pymongo import *
a = {'key1':'value1'}
db1.collection1.insert(a)
print a
Run Code Online (Sandbox Code Playgroud)
这打印
{'_id': ObjectId('53ad61aa06998f07cee687c3'), 'key1': 'value1'}
Run Code Online (Sandbox Code Playgroud)
在控制台上.我知道_id被添加到mongo文档中.但为什么这也添加到我的python字典中呢?我不打算这样做.我想知道这是什么目的?我可以将此字典用于其他目的,并将字典更新为将其插入文档的副作用?如果我必须将这个字典串行化为一个json对象,我会得到一个
ObjectId('53ad610106998f0772adc6cb') is not JSON serializable
Run Code Online (Sandbox Code Playgroud)
错误.在db中插入文档时,insert函数不应该保持字典的值相同.
我在通过 FastAPI 插入 MongoDB 时遇到一些问题。
下面的代码按预期工作。请注意该response变量尚未在 中使用response_to_mongo()。
这model是一个 sklearn ElasticNet 模型。
app = FastAPI()
def response_to_mongo(r: dict):
client = pymongo.MongoClient("mongodb://mongo:27017")
db = client["models"]
model_collection = db["example-model"]
model_collection.insert_one(r)
@app.post("/predict")
async def predict_model(features: List[float]):
prediction = model.predict(
pd.DataFrame(
[features],
columns=model.feature_names_in_,
)
)
response = {"predictions": prediction.tolist()}
response_to_mongo(
{"predictions": prediction.tolist()},
)
return response
Run Code Online (Sandbox Code Playgroud)
但是,当我predict_model()这样写并将response变量传递给response_to_mongo():
@app.post("/predict")
async def predict_model(features: List[float]):
prediction = model.predict(
pd.DataFrame(
[features],
columns=model.feature_names_in_,
)
)
response = {"predictions": prediction.tolist()} …Run Code Online (Sandbox Code Playgroud)