簡體   English   中英

MongoDB:嵌套聚合

[英]MongoDB: Nested aggregation

我有多個 collections:

用戶 - 集合架構

歷史是用戶集合/文檔的子文檔

name: "jacob"
_id: 5fc53209e70f776378cce0c5,
history: [
  {
     _id: 5fc634bee65f96338a63b9e4,
     article: 5fc5f3e6140646c2024f7963,
     created_at: 2010-12-01T12:19:10.121+00:00
  },
  {
    _id: 5fc634d8e65f96338a63b9e5,
    article: 5fc5faaa8b1fffc1f4dec900,
    created_at: 2010-12-01T12:19:36.102+00:00
  }
]

文章 - 集合架構

{
   _id: 5fc5faaa8b1fffc1f4dec900,
   title: "hello there",
   author: 5fc531cae70f776378cce0c4 // Author is related to user collection
},
{
   _id: 5fc5f3e6140646c2024f7963,
   title: "hello wonderland",
   author: 5fc531cae70f776378cce0c4 // Author is related to user collection
}

是否可以先$lookup歷史中的文章,然后$lookup文章的作者? 並且還按歷史日期排序?

所需 Output

...
name: "jacob",
_id: 5fc53209e70f776378cce0c5,
history: [
  {
     _id: 5fc634bee65f96338a63b9e4,
     article: {
        _id: 5fc5faaa8b1fffc1f4dec900,
        title: "hello there",
        author: {
           _id: 5fc531cae70f776378cce0c4,
           name: "melissa"
        }
     },
     created_at: 2010-12-01T12:19:10.121+00:00
  },
  {
    _id: 5fc634d8e65f96338a63b9e5,
    article: {
       _id: 5fc5faaa8b1fffc1f4dec900,
       title: "hello wonderland",
       author: {
          _id: 5fc531cae70f776378ccedsu8,
         name: "omelia",
       }
    },
    created_at: 2010-11-12T2:19:36.102+00:00
  }
]

注意:按日期降序排列

你可以試試,

  • $unwind解構history數組
  • $lookup加入文章集合,讓傳遞文章 id,
    • $match匹配文章 id
    • $lookup加入用戶集合
    • $unwind解構 users 因為它的數組
    • $project顯示必填字段
  • $unwind解構文章數組
  • $sortcreated_at日期排序
  • $group by id 並重建history數組
db.users.aggregate([
  { $unwind: "$history" },
  {
    $lookup: {
      from: "articles",
      let: { articleId: "$history.article" },
      pipeline: [
        { $match: { $expr: { $eq: ["$_id", "$$articleId"] } } },
        {
          $lookup: {
            from: "users",
            localField: "author",
            foreignField: "_id",
            as: "author"
          }
        },
        { $unwind: "$author" },
        {
          $project: {
            _id: 1,
            author: { _id: 1, name: 1 },
            title: 1
          }
        }
      ],
      as: "history.article"
    }
  },
  { $unwind: "$history.article" },
  { $sort: { "history.created_at": -1 } },
  {
    $group: {
      _id: "$_id",
      history: { $push: "$history" },
      name: { $first: "$name" }
    }
  }
])

操場

暫無
暫無

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

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