Home > OS >  MongoDB concat array in a field using Java
MongoDB concat array in a field using Java

Time:04-19

Good morning everyone,

For my company I am developing a java utility to monitor a MariaDB DB and write statistics in a Mongo DB, and this utility will have to work in cronjob every 6 hours. So I set up the environment and I can also write correctly on the mongo DB. But I have a problem ... the mongo db has a collection called stats with the daily_stats field of type array, and after populating it the first time I don't know how to update it by adding elements to the daily_stats field.

Do you have any suggestions or advice?

My Code

  • MongoUtility.java
package com.mspay;

import java.net.UnknownHostException;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientException;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoException;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import java.util.ArrayList;
import java.util.HashMap;
import org.bson.*;
import java.util.Date;
import java.time.LocalDate;
import java.util.Arrays;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.BasicDBList;
import com.mongodb.DBCursor;
import com.mongodb.Block;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;

import com.mongodb.client.MongoCursor;
import static com.mongodb.client.model.Filters.*;
import com.mongodb.client.result.DeleteResult;
import static com.mongodb.client.model.Updates.*;
import com.mongodb.client.result.UpdateResult;
import java.util.List;
import java.text.SimpleDateFormat;
import java.sql.*;

public class MongoUtility {
   static private String host;
   static private String uname;
   static private String psw;
   static private String db;
   static private String comune;

   // costruttore
   public MongoUtility(String h, String usr, String pass, String database, String nomeC) {
      host = h;
      uname = usr;
      psw = pass;
      db = database;
      comune = nomeC;
   }

   public void WriteOnDB(ResultSet rs) throws SQLException{

      Integer nulle = 0, A401 = 0, A402 = 0, A406 = 0, ANNULLO = 0, CN01 = 0, F401 = 0, F4BPER2 = 0, IGNOTO = 0,
            Q41 = 0, Q42 = 0;
      try{
         String caso = null;
         MongoClient mongoClient = new MongoClient(host , 27017);
         DB database = mongoClient.getDB(db);
         DBCollection collection = database.getCollection("stats");
         Date d = new Date();
         d.getTime();

         //recupero i valori giornalieri delle deleghe
         while(rs.next()){
            caso = rs.getString(1);
            if (!rs.getString(2).equals("0")) {
               nulle = Integer.parseInt(rs.getString(2));
            } else if (caso.equals("A401")) {
               A401 = Integer.parseInt(rs.getString(3));
            } else if (caso.equals("A402")) {
               A402 = Integer.parseInt(rs.getString(3));
            } else if (caso.equals("A406")) {
               A406 = Integer.parseInt(rs.getString(3));
            } else if (caso.equals("ANNULLO")) {
               ANNULLO = Integer.parseInt(rs.getString(3));
            } else if (caso.equals("CN01")) {
               CN01 = Integer.parseInt(rs.getString(3));
            } else if (caso.equals("F401")) {
               F401 = Integer.parseInt(rs.getString(3));
            } else if (caso.equals("F4BPER02")) {
               F4BPER2 = Integer.parseInt(rs.getString(3));
            } else if (caso.equals("IGNOTO")) {
               IGNOTO = Integer.parseInt(rs.getString(3));
            } else if (caso.equals("Q41")) {
               Q41 = Integer.parseInt(rs.getString(3));
            } else if (caso.equals("Q42")) {
               Q42 = Integer.parseInt(rs.getString(3));
            }
         }

         //creo il documento mongo
         DBObject doc = new BasicDBObject();
                doc.put("type", "stats");
                doc.put("nome_comune", comune);
         //creo il sotto documento stats e lo popolo con le stats e la data
         Stats st1 = new Stats(d, nulle, A401, A402, A406, ANNULLO, CN01, F401, F4BPER2, IGNOTO, Q41, Q42);
         st1.generateId();
         DBObject dbo;
            ArrayList< DBObject > array = new ArrayList< DBObject >();
            dbo = st1.bsonFromPojo(); array.add( dbo );
         //aggiungo al documento il sotto documento daily_stats
         doc.put( "daily_stats", array );
         //scrivo sul DB le info
         collection.insert(doc, WriteConcern.UNACKNOWLEDGED);

         //collection.findOne(new Document("nome_comune", "name"));

      }catch(MongoClientException e){
            e.printStackTrace();
        }catch(UnknownHostException uh){
            uh.printStackTrace();
        }catch(MongoException me){
            me.printStackTrace();
        }
   }
}

  • Stats.java
package com.mspay;


import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.bson.types.ObjectId;
import java.time.LocalDate;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

public class Stats implements Serializable
{
    private ObjectId _id;
    private Date date_s;
    private Integer NULL;
    private Integer A401;
    private Integer A402;
    private Integer A406;
    private Integer ANNULLO;
    private Integer CN01;
    private Integer F401;
    private Integer F4BPER02;
    private Integer IGNOTO;
    private Integer Q41;
    private Integer Q42;

    public Stats() {}

    public Stats( Date date, Integer NULL, Integer A401, Integer A402,  Integer A406, Integer ANNULLO, Integer CN01, Integer F401, Integer F4BPER02, Integer IGNOTO,  Integer Q41, Integer Q42)
    {
        this.date_s   = date;
        this.NULL   = NULL;
        this.A401 = A401;
        this.A402  = A402;
        this.A406 = A406;
        this.ANNULLO   = ANNULLO;
        this.CN01  = CN01;
        this.F401 = F401;
        this.F4BPER02   = F4BPER02;
        this.IGNOTO  = IGNOTO;
        this.Q41   = Q41;
        this.Q42  = Q42;
    }

    public ObjectId getId() { return this._id; }
    public void setId( ObjectId _id ) { this._id = _id; }
    public void generateId() { if( this._id == null ) this._id = new ObjectId(); }

    public Integer getNULL() { return this.NULL; }
    public void setNULL( Integer NULL ) { this.NULL = NULL; }

    public Integer getA401() { return this.A401; }
    public void setA401( Integer A401 ) { this.A401 = A401; }

    public Integer getA402() { return this.A402; }
    public void setA402( Integer A402 ) { this.A402 = A402; }

    public Integer getA406() { return this.A406; }
    public void setA406( Integer A406 ) { this.A406 = A406; }

    public Integer getANNULLO() { return this.ANNULLO; }
    public void setANNULLO( Integer ANNULLO ) { this.ANNULLO = ANNULLO; }

    public Integer getCN01() { return this.CN01; }
    public void setCN01( Integer CN01 ) { this.CN01 = CN01; }

    public Integer getF401() { return this.F401; }
    public void setF401( Integer F401 ) { this.F401 = F401; }

    public Integer getF4BPER02() { return this.F4BPER02; }
    public void setF4BPER02( Integer F4BPER02 ) { this.F4BPER02 = F4BPER02; }

    public Integer getIGNOTO() { return this.IGNOTO; }
    public void setIGNOTO( Integer IGNOTO ) { this.IGNOTO = IGNOTO; }

    public Integer getQ41() { return this.Q41; }
    public void setQ41( Integer Q41 ) { this.Q41 = Q41; }

    public Integer getQ42() { return this.Q42; }
    public void setQ42( Integer Q42 ) { this.Q42 = Q42; }

    public DBObject bsonFromPojo()
    {
        BasicDBObject document = new BasicDBObject();

        document.put( "_id",    this._id );
        document.put( "date",   this.date_s );
        document.put( "NULL",   this.NULL );
        document.put( "A401", this.A401 );
        document.put( "A402",  this.A402 );
        document.put( "A406",  this.A406 );
        document.put( "ANNULLO",  this.ANNULLO );
        document.put( "CN01",  this.CN01 );
        document.put( "F401",  this.F401 );
        document.put( "F4BPER02",  this.F4BPER02 );
        document.put( "IGNOTO",  this.IGNOTO );
        document.put( "Q41",  this.Q41 );
        document.put( "Q42",  this.Q42 );


        return document;
    }

    public void makePojoFromBson( DBObject bson )
    {
        BasicDBObject b = ( BasicDBObject ) bson;

        this._id    = ( ObjectId ) b.get( "_id" );
        this.date_s   = ( Date )  b.get( "date" );
        this.NULL   = ( Integer )   b.get( "NULL" );
        this.A401 = ( Integer )   b.get( "A401" );
        this.A402  = ( Integer )   b.get( "A402" );
        this.A406  = ( Integer )   b.get( "A406" );
        this.ANNULLO  = ( Integer )   b.get( "ANNULLO" );
        this.CN01  = ( Integer )   b.get( "CN01" );
        this.F401  = ( Integer )   b.get( "F401" );
        this.F4BPER02  = ( Integer )   b.get( "F4BPER02" );
        this.IGNOTO  = ( Integer )   b.get( "IGNOTO" );
        this.Q41  = ( Integer )   b.get( "Q41" );
        this.Q42  = ( Integer )   b.get( "Q42" );
    }
}

CodePudding user response:

Assuming you want the entry to be updated based on the nome_comune property, you could do something like the following:

var query = new BasicDBObject().append("nome_comune", comune);
if(collection.find(query).one() == null) {
    // insert into collection like shown in question
} else {
    var updateFields = new BasicDBObject().append("daily_stats", array);
    var update = new BasicDBObject().append("$push", updateFields);
    collection.update(query, update);
}

So if the document does not exist yet, create it. If it does exist, update it by appending the additional elements.

Alternative Solution

You could also think about using the upsert option, which would avoid having different code for insert and update.

upsert is the third parameter of the function update, the corresponding Javadoc says:

when true, inserts a document if no document matches the update query criteria

It would look something like this:

var query = new BasicDBObject().append("nome_comune", comune);
var updateFields = new BasicDBObject().append("daily_stats", array);
var update = new BasicDBObject().append("$push", updateFields);
collection.update(query, update, true, false);
  • Related