1

我有一个users包含一些文档的集合(),如下所示:

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

我想为user集合中的每个条目创建一个新文档。文档将从这样的通知对象创建:

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

该集合notifications应如下所示:

{
    _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'
}

有没有办法在 mongodb 请求中做到这一点?

4

2 回答 2

2

感谢您在professor79这个问题上帮了我很多忙。

经过一番努力,终于找到了查询。为了成功,我们使用了聚合框架。

唯一需要的 2 个聚合是$project$out。将$out自动处理文档中的新_id内容notification

鉴于此集合名为user

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

我们想为集合中的每个文档创建一个包含相同msg和字段的通知。每个通知都将在集合中,并将其对应的.typeusernotificationsuserId

这是实现这种结果的查询:

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

notifications集合中的输出:

{
    "_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"
}
于 2016-03-02T15:42:00.337 回答
1

因为我们有一些聊天来澄清问题:

执行此操作服务器端所需的步骤:

  1. 第一步 - 匹配 > 获取用户 ID
  2. 根据需要将项目 ID 添加到新文档
  3. out -> 将输出存储在通知集合中
于 2016-02-29T17:10:39.997 回答