簡體   English   中英

mongodb $lookup 用投影查找數組中的嵌套對象

[英]mongodb $lookup for nested object in array with projection

我在聚合管道中使用 $lookup 時遇到問題。

我有 2 個集合、 membersmessages

成員:

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

消息

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

我正在努力做的是,

在 : to:[{status:'Read' , recipient:ObjectId}]查找每個收件人,並從成員集合中填充姓名和電子郵件。

我嘗試了很多不同的東西,比如這個; //

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

許多不同的查詢,包括這個查詢總是為成員返回 [] ('as': 'members')。

只是為了測試我厭倦了貓鼬和 .populate('threads.to.recipient','FirstName') 工作得很好。 但是我不能為此使用貓鼬,我必須使用 MongoDB 的本機 nodejs 驅動程序。

對此的任何建議將不勝感激......

在執行 $lookup 之前,您必須使用$unwind來展平threads數組的結構

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
          }
        }
      ]
    }
  }
])

請參閱 MongoDB Playground 中的工作示例

如果您不想使用 $unwind,請嘗試以下查詢:

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

請參閱 MongoDB Playground 中的工作示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM