how to group in mongoDB and return all fields in result

mongodb group by multiple fields java
mongodb group by array element
spring data mongodb group by multiple fields
mongodb group condition
mongodb group by _id
mongodb match multiple fields
mongoose group by
mongodb aggregate project group

I am using aggregate method in mongoDB to group but when I use $group it returns the only field which I used to group. I have tried $project but it is not working either. I also tried $first and it worked but the result data is now in different format.

The response format I need looks like:

{
    "_id" : ObjectId("5b814b2852d47e00514d6a09"),
    "tags" : [],
    "name" : "name here",
    "rating" : "123456789"
}

and after adding $group in my query.response is like this, the value of _id changes. (and the $group is taking only _id, if i try any other keyword it throws an error of accumulator something. please explain this also.)

{
    "_id" :"name here" //the value of _id changed to the name field which i used in $group condition
}

I have to remove the duplicates in name field, without changing any structure and fields. also I am using nodeJS with mongoose, so please provide the solution that works with it.

You can use below aggregation query.

$$ROOT to keep the whole document per each name followed by $replaceRoot to promote the document to the top.

db.col.aggregate([
  {"$group":{"_id":"$name","doc":{"$first":"$$ROOT"}}},
  {"$replaceRoot":{"newRoot":"$doc"}}
])

mongo group query how to keep fields, In mongo group query, the result shows only the key(s) in arguments. db.​person.aggregate([ { $group: { _id: '$name'}, // pass the set of field to be grouped age Framework, then you'll have to specify which fields to return. should all be the same apart from the unwound field) // on a field called data. MongoDB Projection helps to return the specific fields from the query (or you can say from the MongoDB collection). By default, when we query any collection in MongoDB, it returns all fields in matching documents. Now, at times, we may not want all the records from the collection but a few of them in the result set.

When you group data on any database, it means you want to perform accumulated operation on the required field and the other field which will not be include in accumulated operation will be used in group like

 db.collection.aggregate([{
 $group: {
   _id: { field1: "", field1: "" },
   acc: { $sum: 1 }
 }}]

here in _id object will contains all other fields which you want to hold.

for your data you can try this

db.collection.aggregate([{
    $group: {
        _id: "$name",
        rating: { $first: "$rating" },
        tags: { $first: "$tag" },
        docid: { $first: "$_id" }
    }
},
{
    $project: {
        _id: "$docid",
        name: "$_id",
        rating: 1,
        tags: 1
    }
}])

Mongo group and push: pushing all fields, You can use $$ROOT { $group : { _id : "$author", books: { $push : "$$ROOT" } }}. Found here: how to use mongodb aggregate and retrieve  Mongodb Group by Multiple Fields. The $ group operator is an aggregator that returns a new document. It has its own operator, we can get the field of the current document by $ symbol + field name. To understand the MongoDB group by multiple fields first, let’s have a look at a list of all operators that can be used in $ group: $ sum

You can use this query

db.col.aggregate([
                        {"$group" : {"_id" : "$name","data" : {"$first" : "$$ROOT"}}},
                        {"$project" : {
                            "tags" : "$data.tags",
                            "name" : "$data.name",
                            "rating" : "$data.rating",
                            "_id" : "$data._id"
                            }
                        }])

$group (aggregation), The _id field of each output document contains the unique group by value. The output The operation returns the following result: { "_id" : null, "count" : 8 }. The following aggregation operation groups documents by the item field, calculating the total sale amount per item and returning only the items with total sale amount greater than or equal to 100: copy

user2683814's solution worked for me but in my case, I have a counter accumulator when we replace the newRoot object, the count field is missing in the final stage so I've used $mergeObjects operator to get my count field back.

db.collection.aggregate([
 {
  $group: {
    _id: '$product',
    detail: { $first: '$$ROOT' },
    count: {
      $sum: 1,
    },
  },
},
{
  $replaceRoot: {
    newRoot: { $mergeObjects: [{ count: '$count' }, '$product'] },
  },
}])

$project (aggregation), If you specify the exclusion of a field or fields, all other fields are returned in the output documents. copy The operation results in the following document: copy. MongoDB Project Fields MongoDB Project Fields – In this MongoDB Tutorial, we shall learn to restrict only those fields to return in the result of a query. In MongoDB Query Documents tutorial, we have learnt to filter MongoDB Documents based on a criteria, in which all the fields are returned in the result. But it is not always the case that we need all the fields in the result. We might be

$sum (aggregation), When used in the $group stage, $sum has the following syntax and returns the collective sum of all the numeric values that result from If used on a field that does not exist in any document in the collection, $sum returns 0 for that field. If all​  Starting in MongoDB 3.6, MongoDB drivers and the mongo shell associate all operations with a server session, with the exception of unacknowledged write operations. For operations not explicitly associated with a session (i.e. using Mongo.startSession() ), MongoDB drivers and the mongo shell creates an implicit session and associates it with the operation.

MongoDB Group by Multiple Fields Using Aggregation Function , Mongodb group by multiple fields using Aggregate operation​​ First, the key on which the grouping is based is selected and then the collection is divided into groups according to the selected key value. You can then create a final document by aggregating the documents in each group. If the query bar displays the Project option, you can specify which fields to return in the resulting data. By default, all fields are returned. To set a projection: In the Query Bar, click Options. Enter the projection document into the Project field. To include fields: Specify the field name and set to 1 in the project document.

Grouping documents with $group, We can group by fields that exist in the data, or we can group by expressions that create You should get a list of distinct names. $pushing data into the result. You received this message because you are subscribed to the Google Groups "mongodb-user" group. To post to this group, send email to mongodb-user@googlegroups.com.

Comments
  • post some sample data
  • i simply want to remove the duplicates. assume i receive 50 documents, 20 of them has same name field, which i want only once. ( eg {{"name" : "name1","rating":"123456"},{"name" : "name2","rating":"123456.004"},{"name" : "name1","rating":"12345614.23"}}). i dont want 3rd document as it has same name as 1st and it is duplicate. what should i do in this case?
  • Use $first aggregation to get other fields.
  • problem is when i use group, the value of id changes,i dont want that.
  • eg. {{"_id":ObjectId("123asdf),"name" : "name1","rating":"123456"},{"_id":ObjectId("1234asd),"name" : "name2","rating":"123456.004"},{"_id":ObjectId("12345as"),"name" : "name1","rating":"12345614.23"}} using group returns this response-> {{"_id" : "name1"},{"_id" : "name2"}}. i need the response same as previous, but no dupliacates.
  • Thank you so much, this question really helps me a lot.
  • This is the short and best answer !
  • i simply want to remove the duplicates. assume i receive 50 documents, 20 of them has same name field, which i want only once. ( eg {{"name" : "name1","rating":"123456"},{"name" : "name2","rating":"123456.004"},{"name" : "name1","rating":"12345614.23"}}). i dont want 3rd document as it has same name as 1st and it is duplicate. what should i do in this case?
  • You have different ratings against same name so which one you want to get with group or do you want to all ratings against one name?
  • which ever comes first, the rating is not that important, important thing is that documents must have distinct values of name field.
  • now i am getting "The field 'name' must be an accumulator object" error. if i replace name with _id, it works but it will change the _id value. {"_id" : "name1","rating" : "0.001","tags" : null,"id" : ObjectId("5b814c9752d47e00514e9fcf")}.. the value of _id is changing which i dont want to. the actual value of _id is receiving in "id" field.
  • oh sorry my mistake you are right you will use _id for name then use projection. I'm updating my query