MongoDB 使用 Java 在字段中连接数组

MongoDB concat array in a field using Java

大家早上好,

对于我的公司,我正在开发一个 java 实用程序来监视 MariaDB 数据库并在 Mongo 数据库中写入统计信息,并且该实用程序必须每 6 小时在 cronjob 中运行一次。 于是我搭建了环境,在mongoDB上也能正确写入。 但是我有一个问题......mongo 数据库有一个名为 stats 的集合,其中 daily_stats 字段类型为数组,在第一次填充它之后我不知道如何通过向 daily_stats 字段添加元素来更新它。

您有什么建议或建议吗?

我的代码

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();
        }
   }
}

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" );
    }
}

假设您希望根据 nome_comune 属性 更新条目,您可以执行如下操作:

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", dbo);
    var update = new BasicDBObject().append("$push", updateFields);
    collection.update(query, update);
}

因此,如果文档尚不存在,请创建它。如果确实存在,请通过附加其他元素来更新它。

备选方案

您也可以考虑使用 upsert 选项,这样可以避免插入和更新代码不同。

upsert是函数update的第三个参数,对应的Javadoc说:

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

看起来像这样:

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