在 Flask 中通过 _Id 获取 MongoDB 时出错 [英] Error getting MongoDB by _Id in Flask

查看:80
本文介绍了在 Flask 中通过 _Id 获取 MongoDB 时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以查询我的 MongoDB,我看到_id"值是这样的:

I can query my MongoDB and I see the "_id" value like this:

"_id" : BinData(3,"sFgVQWMKzUiWl5dql62j2g==")

使用 Flask 0.10.1 和 PyMongo 3.0.3 我尝试像这样find_one":

Using Flask 0.10.1 and PyMongo 3.0.3 I attempt to "find_one" like this:

record = db.collection.find_one({'_id': ObjectId("sFgVQWMKzUiWl5dql62j2g==")})

我收到此错误:

bson.errors.InvalidId: 'sFgVQWMKzUiWl5dql62j2g==' is not a valid ObjectId, it must be a 12-byte input or a 24-character hex string

任何帮助将不胜感激.

推荐答案

您正在将 _id 存储为 bindata 并尝试将其检索为 ObjectId,而不是 ObjectId.

You are storing _id as bindata and trying to retrive it as ObjectId, instead of ObjectId.

首先你需要将你的 base64string 转换为二进制,然后尝试搜索.

First you need to convert your base64string to binary and then try to search.

bi = binary.Binary("sFgVQWMKzUiWl5dql62j2g==");
record = db.collection.find_one({'_id': bi});

这对你有用.它会将您的 id 转换为二进制,然后进行比较以获得结果.

This will work for you. It will convert your id to binary then compare to get result.

这篇关于在 Flask 中通过 _Id 获取 MongoDB 时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆