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
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"
}
]
}
]
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