mongodb-aggregation – Cheat Sheet

0

MongoDB database aggregation pipeline example. E.g. $lookup and $group.

$lookup

This aggregation pipeline describes a scenario where to lookup comments to one post. The lookup pipeline section sorts the comments in descending order.

const pipeline = [
    {
        "$match": {
            "_id": ObjectId(id)
        }
    },
    {
        "$lookup": {
            "from": "comments",
            "let": {"id": "$_id"},
            "pipeline": [
                {"$sort": {"date": -1}},
                {"$match": {
                    "$expr": {
                        "$eq": ["$post_id", "$$id"]
                    }
                }}
            ],
            "as": "comments"
        }
    }
]

...
collection.aggregate( pipeline )

$group

const pipeline = [
    { $match: {} },
    { $group: { _id: "$category", content: { $push: "$$ROOT" } }},
    { $sort: { "_id": 1}}
]

...
collection.aggregate( pipeline )
Share.

About Author

Christian Unnerstall

Christian Unnerstall, founder of devshooin.com, enjoys designing and building things that look nice and work well, whether it's websites or services within the interwebs. Have questions - feel free to reach out to him. Enjoy

Leave a Reply