Is there an easy way to "$push" all fields of a document? For example:

Say I have a Mongo collection of books:

{author: "tolstoy", title:"war & peace", price:100, pages:800}
{author: "tolstoy", title:"Ivan Ilyich", price:50,  pages:100}

I'd like to group them by author - for each author, list his entire book objects:

{ author: "tolstoy",
  books: [
     {author: "tolstoy", title:"war & peace", price:100, pages:800}
     {author: "tolstoy", title:"Ivan Ilyich", price:50,  pages:100}
  ]
}

I can achieve this by explicitly pushing all fields:

{$group: {
     _id: "$author",
     books:{$push: {author:"$author", title:"$title", price:"$price", pages:"$pages"}},
}}

But is there any shortcut, something in the lines of:

// Fictional syntax...
{$group: {
    _id: "$author",
    books:{$push: "$.*"},
}}

Solution 1

You can use $$ROOT

{ $group : {
            _id : "$author",
            books: { $push : "$$ROOT" }
        }}

Found here: how to use mongodb aggregate and retrieve entire documents

Solution 2

Actually you cant achieve what you are saying at all, you need $unwind

db.collection.aggregate([
    {$unwind: "$books"},

    {$group: {
         _id: "$author",
         books:{$push: {
             author:"$books.author",
             title:"$books.title",
             price:"$books.price",
             pages:"$books.pages"
         }},
    }}
])

That is how you deal with arrays in aggregation.

And what you are looking for to shortcut typing all of the fields does not exist, yet.

But specifically because of what you have to do then you could not do that anyway as you are in a way, reshaping the document.

Solution 3

If problem is that you don't want to explicitly write all fields (if your document have many fields and you need all of them in result), you could also try to do it with Map-Reduce:

db.books.mapReduce(
    function () { emit(this.author, this); },
    function (key, values) { return { books: values }; },
    { 
        out: { inline: 1 },
        finalize: function (key, reducedVal) { return reducedVal.books; } 
    }
)