MongoDB 通过 findOne 加入集合

我有这个 mongo 数据库查询,它获取对话线程及其参与者详细信息。选项卡是线程的一部分。


var threadObject = await db

        .collection("threads")

        .findOne({ tabs: { $in: [ObjectId("5f2ad2ed59645244cc6a837a")] } });

线程架构:


{

  "_id": {

    "$oid": "5f2ad2bb59645244cc6a8379"

  },

  "thread_participants": [

    {

      "$oid": "5f2ad2a759645244cc6a8377"

    },

    {

      "$oid": "5f2ad2a159645244cc6a8375"

    }

  ],

  "tabs": [

    {

      "$oid": "5f2ad2ed59645244cc6a837a"

    }

  ],

  "date_created": {

    "$date": "2020-08-05T15:39:39.088Z"

  }

}

用户模式:


{

  "_id": {

    "$oid": "5f2ad2a159645244cc6a8375"

  },

  "name": {

    "familyName": "Doe",

    "givenName": "John"

  },

  "email": "johndoe@example.com",

  "display_picture": "url",

  "threads": [

    {

      "$oid": "5f2ad2bb59645244cc6a8379"

    }

  ]

},

{

  "_id": {

    "$oid": "5f2ad2a759645244cc6a8377"

  },

  "name": {

    "familyName": "Doe",

    "givenName": "Monica"

  },

  "email": "monicadoe@example.com",

  "display_picture": "url",

  "threads": [

    {

      "$oid": "5f2ad2bb59645244cc6a8379"

    }

  ]

}

现在的问题是我想检索用户的名字和姓氏以及此 threadObject 的结果。我该如何处理?


智慧大石
浏览 109回答 1
1回答

慕桂英4014372

您可以添加另一个电话:var threadObject = await db        .collection("threads")        .findOne({ tabs: { $in: [ObjectId("5f2ad2ed59645244cc6a837a")] } });var user = await db        .collection("users")        .findOne({ threads: threadObject._id });threadObject.user_name = user.name;...或者您可以使用利用$lookup的聚合管道:var threadObject = await db.collection("threads").aggregate([    {        $match: {            tabs: {$in: [ObjectId("5f2ad2ed59645244cc6a837a")]}        }    },    {        $lookup: {            from: "users",            localField: "_id",            foreignField: "threads",            as: "user"        }    },    {        $unwind: "$user"    },    {        $addFields: {            user_name: "$user.name"        }       },    {        $project: {            user: 0        }    }]).toArray()请注意,聚合将返回一个数组而不是一个对象。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript