Reputation: 2702
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?
Upvotes: 1
Views: 169
Reputation: 46481
You can use $replaceRoot
Book.aggregate([
{ "$match": generateMLabQuery(rawQuery) },
{ "$sort": { "published_date": -1 }},
{ "$group": {
"_id": "$book_id",
"books": { "$first": "$$ROOT" }
}},
{ "$replaceRoot": { "newRoot": "$books" } }
])
Upvotes: 1