Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoengine... query something not in a ListField?

for example..

class Page(Document)
    tags = ListField(StringField())

In this case, we can find out a value in the tags list like this.

Page.objects(tags='coding')

if tags are like ['coding', 'x', 'y'], then the document will be matched...

but My question is how I can find out the value not in the listfield.

my incorrect code would be..

Page.objects(tags!='coding') 

or

Page.objects(tags__not = 'coding')

or

Page.objects(tags__not__in = 'coding')

but.. they don't simply work..

how can I query a document that does not have a given value in a ListField?

like image 656
Anderson Avatar asked Mar 05 '12 10:03

Anderson


People also ask

How do you query in MongoEngine?

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.

Should I use PyMongo or MongoEngine?

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.


2 Answers

To find any pages that don't have the tags coding use the $nin operator:

Page.objects(tags__nin=['coding'])
like image 81
Ross Avatar answered Oct 04 '22 22:10

Ross


I would skip using the build-in mongo syntax on this one and just use a raw query:

Page.objects(__raw__={"tags" : {"$ne" : ['coding']}})

As query get more complicated, your going to wish you set it up like this.

like image 31
josephmisiti Avatar answered Oct 04 '22 21:10

josephmisiti