Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$group with nested array in mongodb

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

like image 768
Chaouki Avatar asked Oct 14 '25 14:10

Chaouki


2 Answers

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 } }
])
like image 150
Ashh Avatar answered Oct 17 '25 12:10

Ashh


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 }
])
like image 25
Senthur Deva Avatar answered Oct 17 '25 13:10

Senthur Deva