如何将基于mongodb的查询转换为基于python的pymongo脚本?

时间:2019-06-04 19:55:27

标签: python mongodb date pymongo

我写了一个mongodb查询来查找开始日期在5年以下的记录。该查询在mongo shell中运行良好。

db.userdetails.aggregate( [ {"$match":{"appid":"58d21f30d2a57d0ec807e012", "data.begin_date":{"$exists":"true"}}},
{ "$project": { "gender":"$data.gender", "birth_date":"$data.birth_date", 
    "membership_type":"$data.membership_type", "postal":"$data.postal", "begin_date":"$data.begin_date", 
    "begin_year":{"$year": "$data.begin_date"} } },
   { "$match": {"begin_year": {"$gt": new Date().getFullYear()-5}} } ] )

现在,我想编写此查询以从python执行。我使用pymongo库。

pipeline = [{"$match":{"appid":"58d21f30d2a57d0ec807e012", "data.begin_date":{"$exists":"true"}}},
            {"$project":{"gender":"$data.gender", "birth_date":"$data.birth_date",
                         "membership_type":"$data.membership_type", "postal":"$data.postal",
                         "begin_date":"$data.begin_date", "begin_year":{"$year": "$data.begin_date"} } },
            {"$match": {"begin_year": {"$gt": datetime.now().year-5}}}]

来自python-

collection_userdetails.aggregate(pipeline)

代码显示错误

**pymongo.errors.OperationFailure: can't convert from BSON type string to Date**

我尝试部分执行查询,并在分析 begin_year“:{” $ year“:” $ data.begin_date“}} 后导致错误。

1 个答案:

答案 0 :(得分:0)

似乎至少有一个文档的$ data.begin_date字段为String而不是Date。

尝试类似:

   db.userdetails.find({"data.begin_date":{$type:2}})

查找数据类型为字符串的文档。开始日期