Node.js mongodb$查找带有投影的数组中的嵌套对象

Node.js mongodb$查找带有投影的数组中的嵌套对象,node.js,mongodb,mongoose,aggregation-framework,Node.js,Mongodb,Mongoose,Aggregation Framework,我在聚合管道中使用$lookup时遇到问题 我有两个收藏,成员和消息 成员: {_id, FirstName, LastName, Email, ...} 信息 { _id:ObjectId('xxx'), createdBy:ObjectId(''), ... threads:[ { message:'' , attachments:[] , from:ObjectId , to:[{status:'Read' , recipient:ObjectId}] }] }

我在聚合管道中使用$lookup时遇到问题

我有两个收藏,
成员
消息

成员:

{_id, FirstName, LastName, Email, ...}
信息

{
  _id:ObjectId('xxx'),
  createdBy:ObjectId(''),
  ...
  threads:[
    {  message:'' , attachments:[] , from:ObjectId , to:[{status:'Read' , recipient:ObjectId}] }]
}
我想做的是

在:
to:[{status:'Read',recipient:ObjectId}]
中查找每个收件人,并填充成员集合中的姓名和电子邮件

我尝试了很多不同的东西,比如这个; //

许多不同的查询(包括此查询)总是为成员返回[]('as':'members')

只是为了测试一下,我厌倦了mongoose和.populate('threads.to.recipient','FirstName')工作得非常好。但是我不能使用mongoose,因为我必须使用MongoDB的原生nodejs驱动程序

如果您在执行$lookup之前需要使用
线程
数组的扁平化结构,请提供任何建议。

db.messages.aggregate([
  {
    $unwind: "$threads"
  },
  {
    $unwind: "$threads.to"
  },
  {
    $lookup: {
      from: "members",
      let: {
        memberId: "$threads.to.recipient"
      },
      as: "members",
      pipeline: [
        {
          $match: {
            $expr: {
              $eq: [
                "$$memberId",
                "$_id"
              ]
            }
          }
        },
        {
          $project: {
            FirstName: 1,
            _id: 1,
            LastName: 1,
            Email: 1
          }
        }
      ]
    }
  }
])

如果不想使用$unwind,请尝试以下查询:

db.messages.aggregate([
  {
    "$lookup": {
      "from": "members",
      "localField": "threads.to.recipient",
      "foreignField": "_id",
      "as": "members"
    }
  }
])

请以mongo shell可执行文件格式添加示例数据。谢谢,请展平已工作线程的结构。我必须使用$unwind,因为使用localField和foreignField进行简单查找不允许我从成员中投影字段。
db.messages.aggregate([
  {
    "$lookup": {
      "from": "members",
      "localField": "threads.to.recipient",
      "foreignField": "_id",
      "as": "members"
    }
  }
])