* Summarize Multiple Nested Fields in MongoDB

Perform aggregate query on multiple nested fields.
Sum income field and output field respectively for each document.

_id

income

output

1

{"cpu":1000,   "mem":500, "mouse":"100"}

{"cpu":1000,
   "mem":600 ,
   "mouse":"120"}

2

{"cpu":2000,   "mem":1000,
   "mouse":50,
   "mainboard:500 }

{"cpu":1500,
   "mem":300 }

The expected result:

ID

INCOME

OUTPUT

1

1600.0

1720.0

2

3550.0

1800.0

To use MongoDB script to handle the multiple fields, you need to store values of income and output fields as arrays using project+filter+cond method under aggregate, split them into records, get the cumulative sum and then group records by _id and concatenate them. This is complicated.

Since grouping by product isn’t required, you can use esProc SPL to get this done. The sum values of each record can be calculated by performing sum operation on sequences.
Download esProc installation package
HERE.

Directions to implement the esProc algorithm:

1. Write SPL script computer.dfx in esProc:

A

B

1

=mongo_open("mongodb://localhost:27017/cookie")

/ Connect to MongoDB database

2

=mongo_shell(A1,"computer.find()").fetch()

/ Get data from computer collection

3

=A2.new(_id:ID,income.array().sum():INCOME,output.array().sum():OUTPUT)

/ Convert fields values under   income and output into sequences and do sums over them

4

>mongo_close(A1)

/ Close database connection

2 Debug and execute the script and view A2’s value as follows:

A2

_id

income

output

1

[1000,500,100]

[1000,500,120]

2

[2000,1000,50,…]

[1500,300]

3. Execute the script and return the final result:

A3

ID

INCOME

OUTPUT

1

1600.0

1720.0

2

3550.0

1800.0

 

esProc provides JDBC interface, so you can easily integrate the script into a Java program:

public
static void doComputer() {
  Connection con = null;
  java.sql.Statement st;
 
  try{
    Class.forName("com.esproc.jdbc.InternalDriver");
    con = DriverManager.getConnection("jdbc:esproc:local://"); 
// Call script computer.dfx
    st=con.createStatement();
ResultSet rst = st.executeQuery("call computer");
 
     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.