10

I have a collection name Alpha_Num, It has following structure. I am trying to find out which Alphabet-Numerals pair will appear maximum number of times ?

If we just go with the data below, pair abcd-123 appears twice so as pair efgh-10001, but the second one is not a valid case for me as it appears in same document.

{
    "_id" : 12345,
    "Alphabet" : "abcd",
        "Numerals" : [
            "123",
            "456",
            "2345"
        ]
}
{
    "_id" : 123456,
    "Alphabet" : "efgh",
    "Numerals" : [
            "10001",
            "10001",
            "1002"
        ]
}

{
    "_id" : 123456567,
    "Alphabet" : "abcd",
        "Numerals" : [
            "123"
        ]
}

I tried to use aggregation frame work, something like below

db.Alpha_Num.aggregate([
                     {"$unwind":"$Numerals"},
                     {"$group":
                              {"_id":{"Alpha":"$Alphabet","Num":"$Numerals"},
                               "count":{$sum:1}}
                     },
                     {"$sort":{"count":-1}}
                     ])

Problem in this query is it gives pair efgh-10001 twice. Question : How to select distinct values from array "Numerals" in the above condition ?

1 Answer 1

23

Problem solved.

db.Alpha_Num.aggregate([{
     "$unwind": "$Numerals"
}, {
     "$group": {
             _id: {
                     "_id": "$_id",
                     "Alpha": "$Alphabet"
             },
             Num: {
                     $addToSet: "$Numerals"
             }
     }
}, {
     "$unwind": "$Num"
}, {
     "$group": {
             _id: {
                     "Alplha": "$_id.Alpha",
                     "Num": "$Num"
             },
             count: {
                     "$sum": 1
             }
     }
}])

Grouping using $addToSet and unwinding again did the trick. Got the answer from one of 10gen online course.

Sign up to request clarification or add additional context in comments.

Comments

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.