【问题标题】:MongoDB insert a document for every documents in another collectionMongoDB 为另一个集合中的每个文档插入一个文档
【发布时间】:2021-03-27 02:52:53
【问题描述】:

我有一个集合 (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 请求中做到这一点?

【问题讨论】:

  • 您将使用什么作为数据库客户端? (node, java, c#) 或者你只想有一个查询来执行?
  • @profesor79 我会使用 nodejs
  • 我不确定我的问题是否正确 1. 用户执行操作 2. 应用程序使用用户 _id 插入通知集合
  • @profesor79 我想为用户集合中的每个用户文档在通知集合中插入一个对象。除了应该有不同的 user_id 之外,每个用户的通知都是相同的。通知应该在通知集合中。

标签: mongodb collections mongodb-query document mongodb-update


【解决方案1】:

感谢professor79 帮助我解决这个问题。

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

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

鉴于此集合名为 user

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

我们希望为user 集合中的每个文档创建一个包含相同msgtype 字段的通知。 每个通知都将位于notifications 集合中,并且将具有其对应的userId 作为参考。

这是实现这样一个结果的查询:

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"
}

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-22
      • 2016-09-22
      • 1970-01-01
      • 2015-09-25
      • 2015-01-18
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      相关资源
      最近更新 更多