tabdulradi
tabdulradi

Reputation: 7596

How to prepend an element to a list in Mongoengine

Mongoengine can push elements to Lists by appending them

BlogPost.objects(id=post.id).update_one(push__tags='nosql')

I want to prepend instead of appending, is there a way ?

Another alternate question to the same problem ..
I can query in a list by position like this

BlogPost.objects(tags__0='nosql')

Is there a way to specify the last element in the list, like -1 index in python lists ?

BlogPost.objects(tags__-1='nosql')# ?.. I wish !

Answers to any of two question will solve my problem. Thanks in advance.

Upvotes: 2

Views: 2285

Answers (2)

Yarneo
Yarneo

Reputation: 3012

The only way I was able to achieve a proper prepend was to use the pythonic way of prepending to a list and then saving the document. Like so:

blog_post = BlogPost.objects.get(id=post.id)
blog_post.tags.insert(0,'nosql')
blog_post.save()

Unfortunately MongoEngine for Python has not yet provided a proper way to use the $position operator for $push.

Upvotes: 1

dcrosta
dcrosta

Reputation: 26258

Neither of those operations is possible, but you can work around it fairly easily by emulating access to the last array element with another field. Suppose your model is:

class BlogPost(Document):
    tags = ListField(StringField())
    # other things

Add a field last_tag:

class BlogPost(Document):
    tags = ListField(StringField())
    last_tag = StringField()
    # other things

Then, when updating:

BlogPost.objects(id=post.id).update_one(push__tags='nosql', set__last_tag='nosql')

And when querying:

BlogPost.objects(last_tag='nosql')

You'll want to make sure that last_tag is indexed, and possibly also tags if you query by that frequently as well.

Upvotes: 1

Related Questions