9
votes

I have the following code:

client = MongoClient(uri)
db = client['my_db']
print(db.collection_names())
#print(db.list_collection_names())

and I get the error

File "C:\Users\gwerner004\eclipse-workspace\MongoTestRasa\FirstTest.py", line 17, in connect print(db.collection_names()) File "C:\Users\gwerner004\AppData\Local\Programs\Python\Python36\lib\site-packages\pymongo\database.py", line 715, in collection_names nameOnly=True, **kws)] File "C:\Users\gwerner004\AppData\Local\Programs\Python\Python36\lib\site-packages\pymongo\database.py", line 677, in list_collections **kwargs) File "C:\Users\gwerner004\AppData\Local\Programs\Python\Python36\lib\site-packages\pymongo\database.py", line 651, in _list_collections cursor = self._command(sock_info, cmd, slave_okay)["cursor"] File "C:\Users\gwerner004\AppData\Local\Programs\Python\Python36\lib\site-packages\pymongo\database.py", line 514, in _command client=self.__client) File "C:\Users\gwerner004\AppData\Local\Programs\Python\Python36\lib\site-packages\pymongo\pool.py", line 579, in command unacknowledged=unacknowledged) File "C:\Users\gwerner004\AppData\Local\Programs\Python\Python36\lib\site-packages\pymongo\network.py", line 150, in command parse_write_concern_error=parse_write_concern_error) File "C:\Users\gwerner004\AppData\Local\Programs\Python\Python36\lib\site-packages\pymongo\helpers.py", line 155, in _check_command_response raise OperationFailure(msg % errmsg, code, response) pymongo.errors.OperationFailure: Unsupported projection option: $substr

Why do I get a failure for such a basic operation? I am running on Windows 10 and using Python 3.6.7. My PyMongo is 3.7.2

1
I have the same problem with list_collections as well, but I use CosmoDB instance - fbjorn
I've found that client['my-collection'].list_collection_names('%d') will give another error saying: AttributeError: 'str' object has no attribute '_txn_read_preference' - H. Pauwelyn

1 Answers

0
votes

The $substr operator works on all currently supported MongoDB versions (2.6-4.4):

> db.foo.aggregate([{$project:{"name": {"$substr": ["$name", 2, -1]}}}])
{ "_id" : ObjectId("5fc032e56bc5b2e2216cdd08"), "name" : "llo" }

Most likely you are using either an ancient MongoDB installation or, per one of the comments, an imitation database like CosmosDB that does not behave as MongoDB itself would (which are also not supported by official MongoDB drivers).