title: How to convert mongodb based query to python based pymongo script?
body: <p>I have written a mongodb query to find the records whose begin date is under 5 years. The query works well in mongo shell.</p>
  
  <pre><code>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}} } ] )
  </code></pre>
  
  <p>Now I want to write this query to execute from python. I used pymongo library for that.</p>
  
  <pre><code>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}}}]
  </code></pre>
  
  <p>From python-</p>
  
  <pre><code>collection_userdetails.aggregate(pipeline)
  </code></pre>
  
  <p>The code shows error</p>
  
  <pre><code>**pymongo.errors.OperationFailure: can't convert from BSON type string to Date**
  </code></pre>
  
  <p>I tried to execute query part by part and after analyzing <strong>begin_year":{"$year": "$data.begin_date"} }</strong> is causing error.</p>