4

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

2 Answers 2

5

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 } }
])
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Thanks for your response! it gives me an error about allowdiskuse !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.