When I run the following in the mongodb shell, it returns the correct number of records:
(searching for the matching "SourceName" within the last 8 days)
mongos> db.fdl.count({ SourceName : "SRC1" , "Created" : { $gte : new Date(new Date().setDate(new Date().getDate()-8)) }})
482
But when I try to run it through python / pymongo, it returns nothing:
import time
import pymongo
myclient = pymongo.MongoClient("mongodb://mylogin:mypass@mymongo.mydomain.net")
mydb = myclient['fdl']
print mydb.fdl.count({ SourceName : "SRC1" , "Created" : { $gte : new Date(new Date().setDate(new Date().getDate()-8)) }})
myclient.close()
then run it:
python query.py
0
In the python code, if I run the query:
print mydb.fdl.count({ SourceName : "SRC1" })
Then I do get a value. So the problem comes from the $gte search.
The problem is not with the count() method, because if I use the find() method, the problem is the same: documents returned in the MongoDB shell, but nothing when calling with python.
Any help would be greatly appreciated !
Thanks a lot in advance 🙂
Best Answer
As per MongoDB pymongo documentation here
The count() method is
deprecated
and not supported in a transaction. Please use count_documents() instead.count(with_limit_and_skip=False)
DEPRECATED - Get the size of the results set for this query.
The count() method is deprecated and not supported in a transaction. Returns the number of documents in the results set for this query. Does not take limit() and skip() into account by default -
set with_limit_and_skip
to True if that is the desired behavior. Raises OperationFailure on a database error.When used with
MongoDB >= 2.6
, count() uses any hint() applied to the query. In the following example the hint is passed to the count command:The count() method obeys the read_preference of the Collection instance on which find() was called.
Changed in version 3.7: Deprecated. Changed in version 2.8: The count() method now supports hint().
count_documents(filter, session=None, kwargs)
Count the number of documents in this collection.
The count_documents() method is supported in a transaction.
All optional parameters should be passed as keyword arguments to this method. Valid options include:
The count_documents() method obeys the read_preference of this Collection.
Note When migrating from count() to count_documents() the following query operators must be replaced:
For your further ref here and here