0

I use mongoengine 0.15.0. In my Inventory Models, there is an ListField 'fruit' that contains EmbeddedDocumentField 'EmbedFruit'. Each EmbedFruit item has 'color' field. I want to access the first item in the ListField.

Can I achieve it by:

result_object = Inventory.objects(__raw__={
    'fruit.0.color': 'red',
}).first()
CandyCrusher
  • 308
  • 1
  • 14
  • 2
    Did you try the `__` syntax? Or did you just presume it would not work? – Neil Lunn Nov 20 '18 at 07:40
  • I will try __ syntax, thanks for reminder! – CandyCrusher Nov 20 '18 at 07:43
  • I have tried result_object = Inventory.objects( fruit__0__color='red').first() – CandyCrusher Nov 20 '18 at 07:48
  • Ahh, you mean you only want **that item** from the list field. MongoEngine does not support that. You actually need to use the raw `_collection` and project the specified index. Should be an example around here somewhere. The question I linked you to before actually showed this with the `$` in projection. And of course there is an answer here, since I did answer this some time ago. – Neil Lunn Nov 20 '18 at 07:50
  • In your case that can even be `FaultReport._get_collection().find({ 'fruit.0.color': 'red' }, { 'fruit.0': 1 })` since the `$` becomes redundant when you already know you want the `0` index returned. – Neil Lunn Nov 20 '18 at 07:54
  • @Neil Lunn What I want is an Inventory item which satisfy the requirement: 'the field 'color' of the first item of EmbeddedDocumentField 'fruit' is equal to 'red' – CandyCrusher Nov 20 '18 at 07:56
  • So that's what you have been given. Read the linked answer. Read the included link to the Github issue on MongoEngine and other notes as to why "projections" are not supported with the object model. – Neil Lunn Nov 20 '18 at 07:58
  • @Neil Lunn Sounds good. Can I use 'find' API in mongoengine? I didn't found it in documentation. – CandyCrusher Nov 20 '18 at 08:00

0 Answers0