I have a document with an array of subdocuments.
These are what the document and the subdocument look like:
class Activity_Comment(EmbeddedDocument):
author_name = StringField()
text_excerpt = StringField()
url = StringField()
class Author_Activity(Document):
author_id = StringField(required=True,primary_key=True)
author_name = StringField()
author_bio = StringField()
latest_comments = ListField(EmbeddedDocumentField(Activity_Comment))
There could be multiple server processes that could modify the the document at the same time. So I want to use update_one
method with upsert=True
.
I also want to restrict the number of subdocuments in the array to 5. It seems this is possible in MongoDB according to these links:
http://docs.mongodb.org/manual/tutorial/limit-number-of-elements-in-updated-array/ http://docs.mongodb.org/manual/reference/operator/update/slice/
These links suggest that I should use $push
to insert the subdocuments into the array and $slice
to limit the array length to the desired value.
However, I haven't been able to figure out how to do this using MongoEngine. I tried the following code
Author_Activity.objects(author_id="1").update_one(push__latest_comments=activity_comment,slice__latest_comments=5, upsert=True)
but it threw the following exception:
Traceback (most recent call last): File "", line 1, in File "/newsoftheworld/local/lib/python2.7/site-packages/mongoengine/queryset/base.py", line 467, in update_one upsert=upsert, multi=False, write_concern=write_concern, **update) File "/newsoftheworld/local/lib/python2.7/site-packages/mongoengine/queryset/base.py", line 430, in update update = transform.update(queryset._document, **update) File "/newsoftheworld/local/lib/python2.7/site-packages/mongoengine/queryset/transform.py", line 181, in update raise InvalidQueryError(e) InvalidQueryError: Cannot resolve field "slice"
What about findAndModify with returted new value? If you reached the limit - remove one.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.