Let say we have a collection transactions which contains some document and documents contain payments which is array of objects.
Now my task is to get the unique types in payments array of every document.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
{ 'id':'74656345' 'payments':[ { 'amount': 200, 'type': 'Debit Card' }, { 'name': 300, 'type': 'Internet Banking' }, { 'name': 300, 'type': 'Credit Card' } ], }, { 'id':'9783475' 'payments':[ { 'amount': 200, 'type': 'Debit Card' }, { 'name': 300, 'type': 'Internet Banking' }, { 'name': 300, 'type': 'UPI' } ], } |
Expected Result: Debit Card, Internet Banking, Credit Card, UPI
which is unique values of payment types in transctions collection and the MongoDB query for that is given below:
1 2 3 4 |
db.transctions.aggregate( {'$unwind':'$payments'}, {"$group" : {"_id": "$payments.type"}} ) |
Here we first unwind the data so that every payments array can be converted to objects and then we are grouping the type of payments document in transctions collection. ...