从查找返回最后一个文档 [英] Return the last Document From a Lookup

查看:62
本文介绍了从查找返回最后一个文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我正在收到针对论坛和所有帖子的回复..[{geoup1,[帖子的数组]},{group2,[帖子的数组]}]

I'm getting response for groups and all post like.. [{geoup1,[post's array]}, {group2,[post's array]}]

如果有任何帖子,我只想将最后添加的帖子添加到帖子收藏夹中

If there is any post I just want last added post into post collection

推荐答案

您可以使用

You can either use $slice

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

或者在MongoDB 3.6中,只需使用 $lookup 以非相关形式:

Or with MongoDB 3.6, just return the last post using $lookup in it's non-correlated form:

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

后者更好,因为您只从实际需要的外部集合中返回文档.

The latter is better because you only return the document from the foreign collection that you actually want.

如果确定要单数",则 $arrayElemAt 可与 $slice 互换,但返回最后一个元素,而不是最后一个元素的数组.您还可以将其添加到第二种形式,以仅从管道中获取一个元素,该元素始终"为数组:

If you are certain you want "singular" then $arrayElemAt is interchangeable with $slice in the initial example but returns the last element instead of the array of the last element only. You can also add it to the second form to just take one element from the pipeline, which is "always" an array:

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

那样的话,它是0索引,而不是最后一个-1.

And that way around it's the 0 index rather than -1 for last.

这篇关于从查找返回最后一个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆