0

I use mongoengine 0.15.0. I have an embedded data structure containing an ListField. I want to access the last/latest item in the list. I am wondering if I can do like this to achieve:

query_set = query_set.filter(fruit__-1__color=red)

If there is any chance can be done by pymongo, it is also welcome.

CandyCrusher
  • 308
  • 1
  • 14
  • It's not supported with a negative index that way. There are ways to write an expression in modern releases, but you really should not do that. Instead "reverse" the order of the array as you store it. In that way, the "latest" is actually the `0` index, and not at a `-1` slice. – Neil Lunn Nov 20 '18 at 04:21
  • @Neil Lunn Thanks for advice. How can I achieve "reverse" when I store? Could u provide any solution? – CandyCrusher Nov 20 '18 at 04:28
  • That would be the very conspicuous box above your question perhaps. – Neil Lunn Nov 20 '18 at 04:34
  • Can I use SortedListField with 'reverse' keyword instead of ListField? – CandyCrusher Nov 20 '18 at 04:36
  • Read the content in the linked answer ( it's actually just one section of the total answer, where the original question was attempting to do the "wrong thing" mentioned earlier ) which actually shows the `$sort` modifier, which is actually what `SortedListField` for MongoEngine actually "modifies" for you. But "sorted" is not for everyone, and the answer content explains why. – Neil Lunn Nov 20 '18 at 04:40
  • finally resolved by using '$push' and '$position' with value 0. just for future reference – CandyCrusher Nov 20 '18 at 07:27

0 Answers0