Return original documents only from mongoose group/aggregation operation

六眼飞鱼酱① 提交于 2019-12-11 06:57:14

问题


I have a filter + group operation on a bunch of documents (books). The grouping is to return only latest versions of books that share the same book_id (name). The below code works, but it's untidy since it returns redundant information:

return Book.aggregate([
    { $match: generateMLabQuery(rawQuery) },
    {
        $sort: {
            "published_date": -1
        }
    },
    {
        $group: {
            _id: "$book_id",
            books: {
                $first: "$$ROOT"
            }
        }
    }
])

I end up with an array of objects that looks like this:

[{ _id: "aedrtgt6854earg864", books: { singleBookObject } }, {...}, {...}]

Essentially I only need the singleBookObject part, which is the original document (and what I'd be getting if I had done only the $match operation). Is there a way to get rid of the redundant _id and books parts within the aggregation pipeline?


回答1:


You can use $replaceRoot

Book.aggregate([
  { "$match": generateMLabQuery(rawQuery) },
  { "$sort": { "published_date": -1 }},
  { "$group": {
    "_id": "$book_id",
    "books": { "$first": "$$ROOT" }
  }},
  { "$replaceRoot": { "newRoot": "$books" } }
])


来源:https://stackoverflow.com/questions/54489090/return-original-documents-only-from-mongoose-group-aggregation-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!