MongoEngine - Query - How to check if ListField is empty or not installed

how to check if ListField() attribute is not set or set for Mongo class?

Thanks!

+9
source share
3 answers

Hi, you can use $ exists and $ 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()) 
+14
source

If you were looking for the opposite question (check if the list contains at least an element that implies that it also exists), here is how you can do this using the dict query to change:

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

According to the MongoEngine documentation, the not operator can be used to override the standard check if it precedes the query statement.

0
source

Not sure, of course, if this is what you mean by an empty or not set 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 

This will output:

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

All Articles