Max Max - 2 years ago 107
Python Question

Get array count of specific document in Pymongo

I've looked around a lot but I couldn't manage to find an answer. It's probably easy but I just can't manage to do this.

I have a collection with some documents and in these documents there are multiple arrays.

I want to know how to query for a document and then do a count for a specific array in that document.
Something like the following:


The result should only return the amount of documents inside the specified array.

Thanks in advance.

Max Max
Answer Source

Because I couldn't find anything useful which does what I want I decided to just use Python for it. To return just the array I used:

result = db.test.find_one({"id":"test"},{'_id':0, 'specific_array':1})

then I converted it too a string:

strresult = str(result)

After that I needed to know the length so if the length was > 16 I gave a command.

if len(strresult) > 16:

This isn't optimal, but it does work, if someone finds a better way I will delete this answer and select the better answer!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download