* Get MongoDB Documents Whose Array Field and the Specified Array Have Common Values
To get documents that meet a specific condition based on a certain array, or to get those whose array type field values contain at least one member of a certain array. There is a given array [English, History, Math]. We want to find information of students who select at least one of the courses in the given array from the following students collection:
students |
_id |
name |
lesson |
1.0 |
Mark |
[English,Chemical,Math,Physics] |
|
2.0 |
Tom |
[Chinese,Chemical,Math,Biology] |
|
3.0 |
Scott |
[Chinese,History] |
|
4.0 |
Andy |
[Chinese,Chemical,Politics,Physics] |
To do the task with MongoDB script, we’ll filter the collection using the combination of filter+input+cond+$in to get the intersections, remove documents whose intersections are null, and then filter the lesson field and display the desired documents. The whole process is roundabout.
esProc SPL, however, will handle the task by performing intersection operations.
Download esProc installation package HERE.
Directions for accomplishing the task with esProc:
1. Write SPL script lesson.dfx in esProc:
A |
B |
|
1 |
[English, History, Math] |
/ Query the conditional array of courses |
2 |
=mongo_open("mongodb://127.0.0.1:27017/raqdb") |
/ Connect to MongoDB database |
3 |
=mongo_shell(A2,"students.find()").fetch() |
/ Query data of collection students |
4 |
=A3.new(_id, name, lesson^A1:lesson).select(lesson!=[]) |
/ Store intersections in lesson filed and remove records with intersection being null |
5 |
>A2.close() |
/ Close database connection |
2. Execute the script and return the following result:
A5 |
_id |
name |
lesson |
1.0 |
Mark |
[English,Math] |
|
2.0 |
Tom |
[Math] |
|
3.0 |
Scott |
[History] |
esProc offers JDBC interface, so you can easily integrate the script into a Java program:
public static void doLesson() {
Connection con = null;
java.sql.Statement st;
try{
Class.forName("com.esproc.jdbc.InternalDriver");
con = DriverManager.getConnection("jdbc:esproc:local://");
// Call script lesson.dfx
st=con.createStatement();
ResultSet rst = st.executeQuery("call lesson");
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/esProcSPL
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