Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group data and get and get all the field back in mongodb [duplicate]

I have collection in a mongodb and want to group invoice by modified and get all the fields in those objects.

{ 
   modified: "11/02/2020",
   stocks: [
             {
              product:{
                 name:"Milk",
                 price: 20
              }
              quantity: 2,
              paid: true
            }
          ]
},
{ 
  modified: "10/02/2020",
  stocks: [
             {
              product:{
                 name:"Sugar",
                 price: 50
              }
              quantity: 1,
              paid: false
            }
   ]
 },
 { 
   modified: "10/02/2020",
   stocks: [
             {
              product:{
                       name:"Butter",
                       price: 10
                    }
              quantity: 5,
              paid: false
            }
        ]
   }

So I tried:

  db.collection.aggregate([{
        $group: {
          _id: "$modified",  
          records: { $push: "$$ROOT" } 
        }
     }
  ])

But It reaggregate on the modifier field being pushed into the records generating duplicates

like image 843
yaxx Avatar asked Sep 20 '25 09:09

yaxx


1 Answers

Demo - https://mongoplayground.net/p/4AGuo5zfF4V

Use $group

db.collection.aggregate([
  {
    $group: { _id: "$grade",  records: { $push: "$$ROOT" } }
  }
])

Output

[
  {
    "_id": "A",
    "records": [
      {
        "_id": ObjectId("5a934e000102030405000000"),
        "grade": "A",
        "name": "John",
        "subject": "English"
      },
      {
        "_id": ObjectId("5a934e000102030405000001"),
        "grade": "A",
        "name": "John1",
        "subject": "English"
      }
    ]
  },
  {
    "_id": "B",
    "records": [
      {
        "_id": ObjectId("5a934e000102030405000002"),
        "grade": "B",
        "name": "JohnB",
        "subject": "English"
      },
      {
        "_id": ObjectId("5a934e000102030405000003"),
        "grade": "B",
        "name": "JohnB1",
        "subject": "English"
      }
    ]
  }
]
like image 95
Tushar Gupta - curioustushar Avatar answered Sep 22 '25 07:09

Tushar Gupta - curioustushar