pa1
pa1

Reputation: 868

Query a exisiting collection by using mongoengine

I am trying to access/query an existing collection in mongo via the following code but i get 0 count even though there are 33 documents in the collection!

from mongoengine import *


class TASK(DynamicDocument):
    pass

connect("try", host="mongodb://x.x.x.x:27017/")

print(task.objects().count()) 

o/p is 0

TASK is a collection in try DB. Has 33 documents can be seen in mongo compass!

Any advice on what i am doing wrong?

TIA!

Upvotes: 0

Views: 313

Answers (1)

bagerard
bagerard

Reputation: 6354

As mentioned in the comment, try forcing the collection name to "TASK" like this:

class TASK(DynamicDocument):
    meta = {'collection': 'TASK'}

Otherwise the underlying collection is "t_a_s_k" and not "TASK" as you would expect. In fact this comes from the fact that usually models are CamelCased (e.g JediWarrior) and mongoengine snake_cases the model name to deduct the collection name (e.g jedi_warrior). See below for a demo of how is the collection named behind the scene in your example:

from mongoengine import *

connect("try", host="mongodb://x.x.x.x:27017/")

class TASK(DynamicDocument):
    pass

collection = TASK._get_collection()
print(collection.name)    # 't_a_s_k'

Upvotes: 1

Related Questions