mongodb对查找结果应用排序

mongodb对查找结果应用排序,mongodb,Mongodb,如果我有user和post收藏 {"_id": 1, "name": "User 1"} {"_id": 2, "name": "User 2"} {"_id": 1, "title": "Post 1", "userId": 1, "createdAt": ISODate("2017-07-24T04:12:54.255Z")} {"_id": 2, "title": "Post 2", "userId": 1, "createdAt": ISODate("2017-07-25T04:12:

如果我有
user
post
收藏

{"_id": 1, "name": "User 1"}
{"_id": 2, "name": "User 2"}

{"_id": 1, "title": "Post 1", "userId": 1, "createdAt": ISODate("2017-07-24T04:12:54.255Z")}
{"_id": 2, "title": "Post 2", "userId": 1, "createdAt": ISODate("2017-07-25T04:12:54.255Z")}
{"_id": 3, "title": "Post 1", "userId": 2, "createdAt": ISODate("2017-07-24T04:12:54.255Z")}
如何列出所有用户的最新帖子?大概是

{
  "_id": 1,
  "name": "User 1",
  "post": {
    "_id": 2,
    "title": "Post 2",
    "userId": 1,
    "createdAt": ISODate("2017-07-25T04:12:54.255Z")
  }
}
我知道我可以很容易地使用$lookup、$unwind post,然后使用$sort by post.createdAt,但这会给我留下多余的用户(用户1将在post 1和post 2中列出两次)


我不知道如何使用$group删除重复项,同时保持其他字段(name、post.title等)

我使用$group和$first解决了重复项

db.getCollection('user').aggregate([
    {$lookup: {from: "post", localField: "_id", foreignField: "userId", as: "post"}},
    {$unwind: { path: "$post", preserveNullAndEmptyArrays: true }},
    {$sort: {"post.createdAt": -1}},
    {$group: {"_id": "$_id", "name": {$first: "$name"}, "post": {$first: "$post"}},
    {$project: {"_id": 1, "name": 1, "post": 1}}
])

请随意发布您的答案

以下是您可以使用的方法

db.getCollection('post').aggregate([
{ $limit: 10 },

{$sort: {"createdAt": -1}},

{$lookup: {from: "user", localField: "userId", foreignField: "_id", as: "user"}},
])

您应该查询按日期排序的帖子并加入用户。因此,如果您想为帖子提供限制,那么您可以。

您可以使用新语法在单个聚合步骤中解决此问题


注意:未经测试的代码,但原则应该明确。

当您不提供限制时,它会起作用。考虑一下,如果我提供了10个帖子的限制和用户集合中的第一个用户,那么最近的12个帖子,那么??完美地工作了,并且还展示了如何使用新的$查找语法。千万!
db.getCollection('users').aggregate([{
    '$lookup': {
      'from': 'posts',
      'let': {
        'userId': '$_id'
      },
      'pipeline': [{
          '$match': { '$expr': { '$eq': ['$userId', '$$userId'] } }
        }, {
          '$sort': {  'createdAt': -1 }
        }, {
          '$limit': 10
        },
      ],
      'as': 'posts'
    }
  }
])