简体   繁体   English

如何在pymongo中获得数组长度?

[英]How can I get array length in pymongo?

I watched this post How can I get the length of a MongoDb array field? 我看过这篇文章如何获得MongoDb数组字段的长度?

I tried these codes: 我试过这些代码:

results=db.posts.find()
results[0].comments.length

I am sure the post and comments exist. 我确信帖子和评论存在。 But it does not work. 但它不起作用。 It will return an error: 它将返回错误:

AttributeError: 'comments' object has no attribute 'length'

How to fix it? 怎么解决?

Pymongo returns documents as dicts. Pymongo以文字形式返回文件。 find() returns an array of dicts. find()返回一个dicts数组。 You need: 你需要:

len(results[0]['comments'])

If you just want the length of the array, do: 如果您只想要数组的长度,请执行以下操作:

result = client.aggregate([
    {
        '$project': {
            'my_array_length': {'$size': '$my_array'}
        }
    }
])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM