Aggregation request to populate

I want to use MongoDB aggregation to populate usersin comments. I can easily use it to populate with an createdByoperator $lookup.

My question is whether the operator can be used $eachin aggregation or something similar to fill userin the comments?

I tried it with Mongo 3.2, but somewhere I read that it will be a new function for something like that in 3.4? I want to run away with $unwindand $groups(I succeeded) and the like so that the request does not become spaghetti code.

Users

{
    "_id" : ObjectId("582c31d4afd9252c8515a88b"),
    "fullName": "test1"
},
{
    "_id" : ObjectId("582c3db0afd9252c8515a88d"),
    "fullName": "test2"
}

and messages :

{
    "_id" : ObjectId("5829cac7e9c0994d3db718f8"),
    "imgUrl": "images/test.jpg",
    "createdBy": ObjectId("582c31d4afd9252c8515a88b"),
    "comments": [
        {
            "_id" : ObjectId("5829cab8e9c0994d3db718f7"),
            "content": "blabla",
            "user": ObjectId("582c31d4afd9252c8515a88b")
        }
    ]
}

expected result :

{
    "_id" : ObjectId("5829cac7e9c0994d3db718f8"),
    "imgUrl": "images/test.jpg",
    "createdBy": ObjectId("582c31d4afd9252c8515a88b"),
    "comments": [
        {
            "_id" : ObjectId("5829cab8e9c0994d3db718f7"),
            "content": "blabla",
            "user": {
                        "_id" : ObjectId("582c31d4afd9252c8515a88b"),
                        "fullName": "test1"
                    }
        }
    ]
}
+4
2

mongodb, .

    db.getCollection('posts').aggregate([
    {"$unwind":{"path":"$comments","preserveNullAndEmptyArrays":true}},
    { $lookup:
            {
                from: 'users',
                localField: 'comments.user',
                foreignField:'_id',
                as: 'comments.user'
            }
    },
    {"$unwind":{"path":"$comments.user","preserveNullAndEmptyArrays":true}},
    {
            $group : {
                _id : "$_id",
                comments : {$push : "$comments"},
                imgUrl : {$first : "$imgUrl"},
                createdBy : {$first : "$createdBy"}
            }
    }

])

, mongodb 3.2.8 $lookup.

+1

.

db.collections.find({}).populate([{path:"comments.user"}]).
0

Source: https://habr.com/ru/post/1661552/


All Articles