亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用聚合管道在 MongoDB 中將功能從一個集合添加到另一個集合

使用聚合管道在 MongoDB 中將功能從一個集合添加到另一個集合

LEATH 2022-08-18 10:55:18
我有兩個系列,它們與另一個相關。一個用戶只能位于一個組中,而一個組可以包含多個用戶。usersgroupsDocument A in users{  _id: 1234,  name: "John Doe"}Document B in users{  _id: 2345,  name: "Jane Roe"}Document G in groups{  _id: 3456,  name: "A Group",  members: [ObjectId("1234"), ObjectId("2345")]}現在,我想使用集合上的聚合管道將字段添加到每個用戶以進行進一步處理。添加的字段應包含用戶所屬組的 ID。users_groupResult for Document A{  _id: 1234,  name: "John Doe",  _group: ObjectId("3456")}Result for Document B{  _id: 2345,  name: "Jane Roe",  _group: ObjectId("3456")}我真的不知道從哪里開始,以及如何以我描述的方式將這兩個系列結合起來。
查看完整描述

1 回答

?
慕田峪4524236

TA貢獻1875條經驗 獲得超5個贊

這應該可以解決問題(https://mongoplayground.net/p/Iu53HQbi7Me):


測試數據:


// users collection

[

    {

      _id: ObjectId("5a934e000102030405000001"),

      name: "John Doe"

    },

    {

      _id: ObjectId("5a934e000102030405000002"),

      name: "Jane Roe"

    }

]


// groups collection

[

    {

      _id: 100,

      name: "A Group",

      members: [

        ObjectId("5a934e000102030405000001"),

        ObjectId("5a934e000102030405000002")

      ]

    }

]

查詢:


db.users.aggregate([

// join the two collections

  {

    $lookup: {

      "from": "groups",

      "localField": "_id",

      "foreignField": "members",

      "as": "membersInfo"

    }

  },

// unwind the membersInfo array

  {

    $unwind: "$membersInfo"

  },

  {

    $project: {

      "_id": {

        $cond: {

          "if": {

            $in: [

              "$_id",

              "$membersInfo.members" // replace _id field based on the members

            ]

          },

          "then": "$_id",

          "else": "No group"

        }

      },

      "name": 1, // mantain this field

      "_group": "$membersInfo._id" // create _group field using the _id of groups collection

    }

  }

])

結果:


[

  {

    "_group": 100,

    "_id": ObjectId("5a934e000102030405000001"),

    "name": "John Doe"

  },

  {

    "_group": 100,

    "_id": ObjectId("5a934e000102030405000002"),

    "name": "Jane Roe"

  }

]


查看完整回答
反對 回復 2022-08-18
  • 1 回答
  • 0 關注
  • 138 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號