pythonaggregatemongoengine

python mongoengine aggregate lookup


Let's say I have two collections, dogs and dog_owners.

dog documents have name and owner attributes, owner being an ObjectId referencing a dog_owner _id attribute.

dog_owners have only a name attribute.

I want to query all dogs but replace the owner attribute which has an id to the reference owner's name.

It's the first time I'm using mongoengine in python, the query would be something like this:

dogs = dogs.objects().aggregate(pipeline)

can somebody help me with the pipeline using $lookup?


Solution

  • There you go in python3.

    Your dog object will have new field dog_owner attached. It won't replace dog.owner, but I think it's good enough.

    cursor = Dog.objects.aggregate([
        {"$lookup": {
            "from": DogOwner._get_collection_name(),
            "localField": "dog_owner_id",
            "foreignField": "_id",
            "as": "dog_owner"
        }},
    ])