I have a collection contains document in this format
{"_id" : NumberLong(567719019),
"date" : ISODate("2018-07-17T09:56:57.000Z"),
"conclusion" : [
{
"rname" : "LAM",
"rulename" : "_OK"
}
],
"indication" : [
{
"rname" : "AM",
"rulename" : "_STABLE"
}
],
"error" : [
{
"errorkey" : "tesd",
"testname" : "d"
},
{
"errorkey" : "v",
"testname" : "c"
},
{
"errorkey" : "td",
"testname" : "d"
},
{
"errorkey" : "va",
"testname" : "c"
}
]
}
So I want to aggregate and group by one or tow element from a table, for example, I want to get all distinct errorkey in my collection and get the maximum appeared error key I tried to work like this
aggregate([{ $group : {_id : { "errorkeyname":
"$error.errorkey"}, count: { $sum: 1 } }},{ $out : "Cllection" }])
but it didn't give a result, any help
You need to $unwind
the error
field and then you can simply use $group
with error.errorkey
db.collection.aggregate([
{ "$unwind": "$error" },
{ "$group": {
"_id": "$error.errorkey",
"count": { "$sum": 1 }
}},
{ "$sort": { "count": 1 } }
])
Try this $unwind $group $push $addToSet $sort $limit
db.col.aggregate([
{ "$unwind": "$error" },
{ "$group": { "_id": null, "distErrKey": { "$addToSet": "$error.errorkey" }, "data": { "$push": "$$ROOT" } } },
{ "$unwind": "$data" },
{ "$group": { "_id": { "errorkeyname": "$data.error.errorkey" }, "count": { "$sum": 1 }, "distErrKeys": { "$first": "$distErrKey" } } },
{ "$sort": { "count": -1 } },
{ "$limit": 1 }
])
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