* How to Perform Row-to-Column Transposition in MongoDB
Row-to-column transposition is often needed in handling MongoDB data in real-world businesses. We have a collection scores that records student scores of English, Math and PE. The computing task is to display scores of subjects in different columns.
CLASS |
STUDENTID |
SUBJECT |
SCORE |
Class one |
1 |
English |
84 |
Class one |
1 |
Math |
77 |
Class one |
1 |
PE |
69 |
Class one |
2 |
English |
81 |
Class one |
2 |
Math |
80 |
… |
The expected result:
CLASS |
STUDENTID |
English |
Math |
PE |
Class one |
1 |
84 |
77 |
69 |
… |
… |
|||
… |
… |
As MongoDB doesn’t offer related API to handle data by group, it’s roundabout to get this done.
esProc SPL has pivot function to handle this directly.
Download esProc installation package HERE.
Directions:
1. Write SPL script scores.dfx in esProc:
A |
B |
|
1 |
=mongo_open("mongodb://127.0.0.1:27017/raqdb") |
/ Connect to MongoDB database |
2 |
=mongo_shell(A1,"scores.find(,{_id:0})") |
/ Get data of scores collection |
3 |
=A2.pivot(CLASS,STUDENTID;SUBJECT,SCORE) |
/ Perform row-to-column transposition |
4 |
=A3.pivot@r(CLASS,STUDENTID;SUBJECT,SCORE) |
/ Perform column -to- row transposition |
5 |
>A1.close() |
/ Close database connection |
2. Execute the script to return the final result:
A3 |
CLASS |
STUDENTID |
English |
Math |
PE |
Class one |
1 |
84 |
77 |
69 |
|
Class one |
2 |
81 |
80 |
97 |
|
Class one |
3 |
75 |
86 |
67 |
|
… |
A4 |
CLASS |
STUDENTID |
SUBJECT |
SCORE |
Class one |
1 |
English |
84 |
|
Class one |
1 |
Math |
77 |
|
Class one |
1 |
PE |
69 |
|
Class one |
2 |
English |
81 |
|
Class one |
2 |
Math |
80 |
|
… |
pivot()function group rows by the given CLASS field and STUDENTID field, uses SUBJECT values as new columns and populates each of score values in corresponding record under the right field. In this way the row-to-column transposition is done right. On the contrary, pivot@r() function performs column-to-row transposition.
esProc provides JDBC interface to let you integrate the script into a Java program conveniently:
public static void doWork() {
Connection con = null;
java.sql.Statement st;
try{
Class.forName("com.esproc.jdbc.InternalDriver");
con = DriverManager.getConnection("jdbc:esproc:local://");
// Call script scores.dfx
st=con.createStatement();
ResultSet rst = st.executeQuery("call scores");
System.out.println(rst);
} catch(Exception e){
System.out.println(e);
} finally{
// Close database connection
if (con!= null) {
try {
con.close();
} catch(Exception e) {
System.out.println(e);
}
}
}
}
Read How to Call an SPL Script in Java to learn more about integration of esProc SPL script into a Java program.
SPL Official Website 👉 https://www.scudata.com
SPL Feedback and Help 👉 https://www.reddit.com/r/esProc_SPL
SPL Learning Material 👉 https://c.scudata.com
SPL Source Code and Package 👉 https://github.com/SPLWare/esProc
Discord 👉 https://discord.gg/cFTcUNs7
Youtube 👉 https://www.youtube.com/@esProc_SPL