从查找中返回最后一个文档

Smi*_*tel 2 mongoose mongodb mongodb-query aggregation-framework

db.groups.aggregate([
   {
     $lookup:
       {
         from: "posts",
         localField: "_id",
         foreignField: "group",
         as: "post"
       }
  }
])
Run Code Online (Sandbox Code Playgroud)

我收到群组和所有帖子的回复,例如.. [{geoup1,[post's array]}, {group2,[post's array]}]

如果有任何帖子,我只想将最后添加的帖子添加到帖子集合中

Nei*_*unn 11

您可以使用 $slice

db.groups.aggregate([
   { "$lookup": {
     "from": "posts",
     "localField": "_id",
     "foreignField": "group",
     "as": "post"
   }},
   { "$addFields": {
     "post": { "$slice": ["$post", -1] }
   }}
])
Run Code Online (Sandbox Code Playgroud)

或者使用 MongoDB 3.6,只需使用$lookup非相关形式返回最后一篇文章:

db.groups.aggregate([
   { "$lookup": {
     "from": "posts",
     "as": "post",
     "let": { "id": "$_id" },
     "pipeline": [
       { "$match": { 
          "$expr": { "$eq": [ "$$id", "$group" ] }
       }},
       { "$sort": { "_id": -1 } },
       { "$limit": 1 }
     ]
   }}
])
Run Code Online (Sandbox Code Playgroud)

后者更好,因为您只从您真正想要的外部集合中返回文档。

如果您确定您想要“单数”,那么在初始示例中$arrayElemAt可以与它互换,$slice但只返回最后一个元素而不是最后一个元素的数组。您还可以将它添加到第二种形式,以便从管道中取出一个元素,它“始终”是一个数组:

db.groups.aggregate([
   { "$lookup": {
     "from": "posts",
     "as": "post",
     "let": { "id": "$_id" },
     "pipeline": [
       { "$match": { 
          "$expr": { "$eq": [ "$$id", "$group" ] }
       }},
       { "$sort": { "_id": -1 } },
       { "$limit": 1 }
     ]
   }},
   { "$addFields": {
     "post": { "$arrayElemAt": [ "$post", 0 ] }
   }}
])
Run Code Online (Sandbox Code Playgroud)

这样一来,它就是0索引而不是-1最后一个。