1

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?

Samuel Rondeau-Millaire
  • 1,100
  • 2
  • 13
  • 24

2 Answers2

2

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"
}
SnekNOTSnake
  • 1,157
  • 12
  • 24
Samuel Rondeau-Millaire
  • 1,100
  • 2
  • 13
  • 24
1

As we have some chat to clarify problem:

the steps are needed to perform this operation server side:

  1. first step - match > get users id
  2. project ids to new documents as required
  3. out -> store output in notification collection
profesor79
  • 9,213
  • 3
  • 31
  • 52