I'm new to pymongo and can't quite wrap my head around the logic of creating a nested group and match. Im trying to find all the unique models types and then create a list of the logical names used for the models. The output that I want to create, or close to it. { {"Model-1", {Devices: ["Name-1","Name-4"]}, {"Model-2", {Devices: ["Name-2","Name-3"]} } Mongo DB Data: [ { "_id": "1", "cdate": { "$date": "2023-11-16T00:00:00.000Z" }, "AP Name": "Name-1", "Model": "Model-1" }, { "_id": "2", "cdate": { "$date": "2023-11-16T00:00:00.000Z" }, "AP Name": "Name-2", "Model": "Model-2" }, { "_id": "3", "cdate": { "$date": "2023-11-16T00:00:00.000Z" }, "AP Name": "Name-3", "Model": "Model-2" }, { "_id": "4", "cdate": { "$date": "2023-11-16T00:00:00.000Z" }, "AP Name": "Name-4", "Model": "Model-1" } ] My code: I dont think this is the best way to do this.. so any help or suggestions woudld be great. def mongo_aggregate_tags(foo_coll, foo_keyword, foo_match, x): agg_sites = foo_coll.aggregate( [ {"$match": {f"{foo_match}": x}}, {"$group": {"_id": f"${foo_keyword}"}}, {"$sort": {foo_keyword: 1}}, ] ) return agg_sites for f_item in coll_inv.distinct("Model"): for x in mongo_aggregate_tags(coll_inv, "Model", "AP Name", f_item): print(x, " ", f_item) print(type(x)) The output I actually get looks like this: {'_id': 'Model-1'} Name-1 {'_id': 'Model-1'} Name-4 {'_id': 'Model-2'} Name-2 {'_id': 'Model-2'} Name-3 Continue reading...