how do I check if an ListField()
attribute of a Mongo Class is not set or empty?
Thanks!
The connect() function returns a MongoClient object. Using list_database_names() method available to this object, we can retrieve number of databases on the server. It is also possible to obtain list of collections in a database, using list_collection_names() method.
Both PyMongo and MongoEngine can be used to access data from a MongoDB database. However, they work in very different ways and offer different features. PyMongo is the MongoDB recommended library. It makes it easy to use MongoDB documents and maps directly to the familiar MongoDB Query Language.
Deleting documents. To delete a document, call the delete() method. Note that this will only work if the document exists in the database and has a valid id .
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With