MongoDB - MongoEngine - How do I follow a reference from "the other side"?
Here is a test case showing how to query it:
import unittestfrom mongoengine import *class StackOverFlowTest(unittest.TestCase): def setUp(self): conn = connect(db='mongoenginetest') def test_one_two_many(self): class MyClass(Document): other_classes = ListField(ReferenceField("OtherClass")) class OtherClass(Document): text = StringField() MyClass.drop_collection() OtherClass.drop_collection() o1 = OtherClass(text='one').save() o2 = OtherClass(text='two').save() m = MyClass(other_classes=[o1, o2]).save() # Lookup MyClass that has o1 in its other_classes self.assertEqual(m, MyClass.objects.get(other_classes=o1)) # Lookup MyClass where either o1 or o2 matches self.assertEqual(m, MyClass.objects.get(other_classes__in=[o1, o2]))
The main question is do you need to store a list of references in the MyClass
? It might be more efficient to store the relationship just on OtherClass
..
Try this query:
oc = Other_Class()MyClass.objects.find( other_classes__all = [oc.id] )
While thinking about my problem I came up with a solution.
I just add the ID of my referenced class to my model.
Here's an example:
class MyClass(Document): ... other_classes = ListField(ReferenceField(Other_Class))class Other_Class(Document): myclass = ReferenceField(MyClass)
I'm not quite sure if this is the Mongo-way to do it but I'm pretty sure it works :)
Optionally you can omit the other_classes
attribute in MyClass
to avoid redundancy but then you need a query like this to get the "child" objects:
Other_Class.objects(myclass = myclass.id)