skip to Main Content

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?

ID are stored into csv file. Need to search this ID’s in mongodb collection and if found fetch the document and do the grouping based on ID field.

Input .csv file

**ID**
1
2

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

2

Answers


  1. 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']
    
    Login or Signup to reply.
  2. 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([
        {
            '$match':{ID: {$in: idArray}}
        },
        {
            '$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'
                    ]
                }
            }
        }
    ])
    

    you can use a variable to get all the ids that you have in your csv file, and later use that variable in match stage .

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search