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質問を手伝ってくれてありがとう。

多くの努力の後、クエリが見つかりました。成功するために、集約フレームワークを使用しました。

必要な集計は$projectとの 2 つだけ$outです。は、ドキュメント内$outの新しいものを自動的に処理します。_idnotification

という名前のこのコレクションを考えるとuser:

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

コレクション内のすべてのドキュメントに対して同じmsgandフィールドを含む通知を作成したいと考えています。各通知はコレクションに含まれ、対応する参照として保持されます。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 に答える