检查列表是否不是空的pymong

2024-04-26 11:28:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为mongo中的特定id返回一个名为list_followers的列表,该列表位于数据库中。但是,数据库的一些文档的列表大小为零。因此,我得到了list_followers的key_错误。在

list_of_ids = []
for cursor in collection.find({ "list_followers" : { "$exists":True}}):
    id = cursor['_id']['uid']
    list_of_ids.append(id)
    followers = cursor['list_followers']
    print len(followers)

print len(list_of_ids)

我怎样才能只查询列表跟随者大于零的游标?我试过{"list_followers":{"$gt":0}}或{},但那不是我想要的。在


Tags: ofkey文档id数据库ids列表for
3条回答

您正在寻找$size运算符。您还应该在查询中使用$exists,因为没有它,它甚至可以匹配没有字段list_followers的文档:

collection.find({'list_followers': {'$not' : {'$size' :  0}, '$exists' : True}})

您可以检查^{}是否不等于0:

The $size operator matches any array with the number of elements specified by the argument.

collection.find({"list_followers": {"$not": {'$size': 0}, "$exists": True}})

感谢@Christian p关于exists需求的注释。在


{cd3>或者,可以检查第一个元素}:

^{pr2}$

试试这个

collection.find({'list_followers': {'$not': {'$size': 0}}}))

相关问题 更多 >