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: "$.*"}, }}
The $push operator appends a specified value to an array. The $push operator has the form: { $push: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.
In MongoDB, the $push operator is used to appends a specified value to an array. If the mentioned field is absent in the document to update, the $push operator add it as a new field and includes mentioned value as its element. If the updating field is not an array type field the operation failed.
What is Aggregation in MongoDB? Aggregation is a way of processing a large number of documents in a collection by means of passing them through different stages. The stages make up what is known as a pipeline. The stages in a pipeline can filter, sort, group, reshape and modify documents that pass through the pipeline.
You can use $$ROOT
{ $group : { _id : "$author", books: { $push : "$$ROOT" } }}
Found here: how to use mongodb aggregate and retrieve entire documents
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With