Search code examples
mongodbcollectionsmongodb-querydocumentmongodb-update

MongoDB insert a document for every documents in another collection


I have a collection (users) containing some documents like so :

{
    _id: ObjectId("56d45406be05db4022be51f9"),
    morecontent : ""
},
{
    _id: ObjectId("56d45406be05db3021be32e3"),
    morecontent : ""
}

I would like to create a new document for every entry in the user collection. The documents would be created from a notification object like this :

{
    type: 'alert',
    msg: 'This is important'
}

The collection notifications should look something like this :

{
    _id: ObjectId("56d45406be05db3021bf20a1"),
    someoldcontent: "This was here before the request"
},
{
    _id : ObjectId("56d45406be05db4022be20b1"),
    user: ObjectId("56d45406be05db4022be51f9"),
    type: 'alert',
    msg: 'This is important'
},
{
    _id : ObjectId("56d45406be05db3021be32e3"),
    user: ObjectId("56d45406be05db3021be32e3"),
    type: 'alert',
    msg: 'This is important'
}

Is there any way to do this in a mongodb request?


Solution

  • Thanks to professor79 for helping me a lot with the question.

    After lots of effort, the query was found. We used the aggregation framework in order to succeed.

    The only 2 aggregations needed are $project and $out. The $out will automatically take care of the new _id in the notification document.

    Given this collection named user :

    {
        _id: ObjectId("56d45406be05db4022be51f9"),
        morecontent : ""
    },
    {
        _id: ObjectId("56d45406be05db3021be32e3"),
        morecontent : ""
    }
    

    We want to create a notification containing the same msg and type field for every document in the user collection. Each notifications will be in the notifications collection an will have as a reference its corresponding userId.

    Here is the query to achieve such a result :

    db.user.aggregate([
        {
            $project: {
                userId: '$_id',
                type: { $literal: 'danger' },
                msg: { $literal: 'This is a message' },
            },
        },
        { $out: 'notifications' },
    ])
    

    The output in notifications collection:

    {
        "_id" : ObjectId("56d6112e197b4ea11a87de1a"),
        "userId" : ObjectId("56d45406be05db4022be51f9"),
        "type" : "danger",
        "msg" : "This is a message"
    },
    {
        "_id" : ObjectId("56d6112e197b4ea11a87de1b"),
        "userId" : ObjectId("56d45406be05db3021be32e3"),
        "type" : "danger",
        "msg" : "This is a message"
    }