MongoEngine - 查询 - 如何检查ListField是否为空

时间:2012-08-08 15:27:38

标签: mongodb mongoengine listfield

如何检查Mongo类的ListField()属性是否未设置或为空?

谢谢!

3 个答案:

答案 0 :(得分:13)

您好,您可以使用$exists$size

import unittest
from mongoengine import *

class Test(unittest.TestCase):

    def setUp(self):
        conn = connect(db='mongoenginetest')

    def test_list_exists_or_has_size(self):

        class Post(Document):
            title = StringField(required=True)
            tags = ListField(StringField())

        Post.drop_collection()

        Post(title="Hello Stackoverflow").save()
        Post(title="Hello twitter", tags=[]).save()
        Post(title="Hello world", tags=['post', 'blog']).save()

        self.assertEqual(2, Post.objects(
                                Q(tags__exists=False) |
                                Q(tags__size=0)).count())

答案 1 :(得分:0)

如果您正在寻找相反的问题(请检查列表中是否至少包含一个元素,这意味着它也存在),这是使用查询字典进行更改的方法:

query = {}
query['tags__exists'] = True
query['tags__not__size'] = 0
for post in Post.objects(**query):
    print(post)

根据MongoEngine documentationnot运算符可用于否定标准检查,只要它在查询运算符之前即可。

答案 2 :(得分:-1)

不确定这是否是 empty 未设置 ListField的意思:

from mongoengine import *

connect('tumblelog')


class Post(Document):
    title = StringField(required=True)
    tags = ListField(StringField())


post1 = Post(title='Fun with MongoEngine', tags=['mongodb', 'mongoengine'])
post1.save()

for post in Post.objects:
    print post.title
    if not post.tags:
        print '-post has no tags'
    else:
        print post.tags

这将输出:

Fun with MongoEngine
[u'mongodb', u'mongoengine']
Fun with MongoEngine no tags
-post has no tags