Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

mongodb - Return the last Document From a Lookup

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can either use $slice

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

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.

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...