我有一个具有以下结构的数据库:
{
"_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"
}
]
}
我需要更新嵌入文档的IsContingenciaBD参数。
在mongo中更改此值的查询如下:
db.PropertiesMQ.update({"NOMBRE_HOST" : "Base1", "BASEDATOS.SID" : "PRODM3"}, {$set: {"BASEDATOS.$.IsContingenciaBD" : "true"}})
我尝试使用以下代码在Java中复制此查询:
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();
执行它时,出现以下错误:
线程“主”中的异常java.lang.IllegalArgumentException:无效
BSON字段名称BASEDATOS。$。IsContingenciaBD
最佳答案
看起来像您在updateOne方法中使用数据。相反,它应该是命令BasicDBObject。像下面一样
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