0
votes

I have a database with the following structure:

{
    "_id" : ObjectId("5d54608122474f8d2927d898"),
    "NOMBRE_HOST" : "Base1",
    "IsContingenciaODA" : "false",
    "puerto" : "1532",
    "HostContigencia" : "Base2",
    "BASEDATOS" : [
        {
            "SID" : "REPOS",
            "IsContingenciaBD" : "false",
            "host" : "Base3",
            "puerto" : "1111"
        },
        {
            "SID" : "PRODM2",
            "IsContingenciaBD" : "false",
            "host" : "nb",
            "puerto" : "1111"
        },
        {
            "SID" : "PRODM3",
            "IsContingenciaBD" : "true",
            "host" : "Base4",
            "puerto" : "999"
        }
    ]
}
{
    "_id" : ObjectId("5d54608122474f8d2927d899"),
    "NOMBRE_HOST" : "172.0.0.1",
    "IsContingenciaODA" : "false",
    "puerto" : "1532",
    "HostContigencia" : "172.10.0.1",
    "BASEDATOS" : [
        {
            "SID" : "Base6",
            "IsContingenciaBD" : "false",
            "host" : "172.7.0.1",
            "puerto" : "999"
        }
    ]
}

I need to update the IsContingenciaBD parameter of the embedded documents. The query that change this value in mongo is the following:

db.PropertiesMQ.update({"NOMBRE_HOST" : "Base1", "BASEDATOS.SID" : "PRODM3"}, {$set: {"BASEDATOS.$.IsContingenciaBD" : "true"}})

I tried to replicate this query in java with the following code:

        MongoClient client = new MongoClient("my_ip", "my_port");
        MongoDatabase mongodb = client.getDatabase("prueba");
        MongoCollection<Document> collection = mongodb.getCollection("PropertiesMQ");
        BasicDBObject filter = new BasicDBObject();
        filter.put("NOMBRE_HOST", host);
        filter.put("BASEDATOS.SID", sid);
        BasicDBObject data = new BasicDBObject();
        data.put("BASEDATOS.$.IsContingenciaBD", state);
        BasicDBObject command = new BasicDBObject();
        command.put("$set", data);
        System.out.println(filter + ", " + command);
        collection.updateOne(filter, data);
        client.close();

When executing it I get the following error:

Exception in thread "main" java.lang.IllegalArgumentException: Invalid BSON field name BASEDATOS.$.IsContingenciaBD

1

1 Answers

1
votes

Looks like your using data inside updateOne method. instead it should be command BasicDBObject. Like below,

    MongoCollection<Document> collection = mongodb.getCollection("PropertiesMQ");
    BasicDBObject filter = new BasicDBObject();
    filter.put("NOMBRE_HOST", host);
    filter.put("BASEDATOS.SID", sid);
    BasicDBObject data = new BasicDBObject();
    data.put("BASEDATOS.$.IsContingenciaBD", state);
    BasicDBObject command = new BasicDBObject();
    command.put("$set", data);
    System.out.println(filter + ", " + command);
    collection.updateOne(filter, command); //Use Command instead of data