Mongo group and push: pushing all fields

Mongodb

Mongodb Problem Overview


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: "$.*"},
}}

Mongodb Solutions


Solution 1 - Mongodb

You can use $$ROOT

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

Found here: https://stackoverflow.com/questions/22359742/how-to-use-mongodb-aggregate-and-retrieve-entire-documents

Solution 2 - Mongodb

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 - Mongodb

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPelit MamaniView Question on Stackoverflow
Solution 1 - MongodbJurjen LadeniusView Answer on Stackoverflow
Solution 2 - MongodbNeil LunnView Answer on Stackoverflow
Solution 3 - MongodbIvan.SrbView Answer on Stackoverflow