Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo group and push: pushing all fields

Tags:

mongodb

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: "$.*"}, }} 
like image 514
Pelit Mamani Avatar asked Mar 03 '14 15:03

Pelit Mamani


People also ask

What does $Push do in MongoDB?

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.

How do I push data into an array in MongoDB?

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 aggression in MongoDB?

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.


2 Answers

You can use $$ROOT

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

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

like image 51
Jurjen Ladenius Avatar answered Oct 21 '22 14:10

Jurjen Ladenius


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.

like image 33
Neil Lunn Avatar answered Oct 21 '22 13:10

Neil Lunn