how to group records based on ID and put same ID record into set(set1,set2,etc). Input data will be in form on list of dictionaries. will read the input data from MongodDb database. I wish to group objects based on id. I mean, object with the same id should be in a group. Is there any idea?
Input Data
[
{
ID:1,
Name: ABC,
Age:23,
City:XYZ
},
{
ID:1,
Name: DEF,
Age:24,
City:XXX
},
{
ID:2,
Name: GHI,
Age:25,
City:YYY
},
{
ID:2,
Name: CBA,
Age:27,
City:ZZZ
}
]
**Expected Output **
[
{
ID:1,
Name: ABC,
Age:23,
City:XYZ,
Set_ID : Set1
},
{
ID:1,
Name: DEF,
Age:24,
City:XXX,
Set_ID : Set1
},
{
ID:2,
Name: GHI,
Age:25,
City:YYY,
Set_ID : Set2
},
{
ID:2,
Name: CBA,
Age:27,
City:ZZZ,
Set_ID : Set2
}
]
CodePudding user response:
Could you clarify your question? Looking at your input and output the following trivial code would do the job:
for d in input:
d['Set_ID'] = "Set" d['ID']
CodePudding user response:
you can use aggregation for the set property you want, but since it is a number you have to convert it into string first.
if it is string you can skip the second stage.
db.collection.aggreagate([
{
'$group': {
'_id': '$ID',
'ID': {
'$first': '$ID'
},
'Name': {
'$first': '$Name'
},
'Age': {
'$first': '$Age'
},
'City': {
'$first': '$City'
}
}
}, {
'$addFields': {
'SET_ID': {
'$toString': '$ID'
}
}
}, {
'$addFields': {
'SET': {
'$concat': [
'Set', '$SET_ID'
]
}
}
}
])