9

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

谢谢!

4

3 回答 3

16

嗨,您可以使用$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())
于 2012-08-13T16:49:04.857 回答
1

如果您正在寻找相反的问题(检查列​​表是否至少包含一个暗示它也存在的元素),那么您可以使用查询字典进行更改:

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

根据 MongoEngine文档,该not运算符可用于否定标准检查,只要它位于查询运算符之前。

于 2019-10-07T16:48:49.140 回答
-1

不完全确定这是否是或未设置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
于 2012-08-13T15:26:31.643 回答