我的剧本有点小错误:
BasicDBObject change = new BasicDBObject();
BasicDBObject account =
new BasicDBObject().append("$set", new BasicDBObject().append("status", 0));
account.append("pos.X", getX());
account.append("pos.Y", getY());
account.append("pos.Z", getZ());
change.append("pseudo", gPlayer);
coll.update(change, account);
mongoDB的结构是:
{
pseudo: "pseudo"
email: "email"
password: "password"
status: "1"
pos: [
{X: "90.45}
{Y: "90.45}
{Z: "90.45}
]
}
但这不起作用!没有修改任何值。
感谢您的帮助。
答案 0 :(得分:3)
Java是一种非常冗长的语言,有时最简单的方法是首先使用JS shell编写查询,确保它按照需要执行,然后将其转换为Java。
通过将System.out.println(account.toString())添加到Java代码中,我可以看到您的Update文档如下所示,这是无效的:
{ "$set" : { "status" : 0} , "pos.X" : "90.45" , "pos.Y" : "90.45" , "pos.Z" : "90.45"}
从您的问题来看,您希望更新的文档看起来并不完全清楚,但我猜您想要修改“status”和“pos.0.X”的值,“pos” .1.Y“和”pos.2.Z“。由于X,Y和Z都作为单独的嵌入文档存储在数组中,因此必须通过它们的位置引用它们才能同时更新。如果可能,您可能会发现最好重新排列文档结构,使X,Y和Z都存储在同一文档中,如下所示:
"pos" : {
"X" : "0",
"Y" : "0",
"Z" : "0"
}
通过这种方式,您可以使用点符号pos.X,pos.Y,pos.Z更轻松地访问每个变量,从您的帖子看起来就像您想要的那样。有关嵌入式文档的更多信息,请参见“Dot Notation(Reaching into Objects)”文档: http://www.mongodb.org/display/DOCS/Dot+Notation+%28Reaching+into+Objects%29
这是一个Update语句,它将修改上述值:
> db.pseudo.find({ "pseudo" : "gPlayer"}).pretty()
{
"_id" : ObjectId("4f904ebb5bebd4375b759c90"),
"email" : "email",
"password" : "password",
"pos" : [
{
"X" : "90.45"
},
{
"Y" : "90.45"
},
{
"Z" : "90.45"
}
],
"pseudo" : "gPlayer",
"status" : "1"
}
> db.pseudo.update({"pseudo" : "gPlayer"}, { "$set" : { "status" : 0 , "pos.0.X" : "0" , "pos.1.Y" : "0" , "pos.2.Z" : "0"}})
> db.pseudo.find({ "pseudo" : "gPlayer"}).pretty()
{
"_id" : ObjectId("4f904ebb5bebd4375b759c90"),
"email" : "email",
"password" : "password",
"pos" : [
{
"X" : "0"
},
{
"Y" : "0"
},
{
"Z" : "0"
}
],
"pseudo" : "gPlayer",
"status" : 0
}
>
转换为Java,这是:
BasicDBObject change = new BasicDBObject("pseudo", "gPlayer");
BasicDBObject setDoc = new BasicDBObject();
setDoc.append("status", "0");
setDoc.append("pos.0.X", "0");
setDoc.append("pos.1.Y", "0");
setDoc.append("pos.2.Z", "0");
BasicDBObject account = new BasicDBObject("$set", setDoc);
coll.update(change, account);
我意识到我猜到了你想要做的更新,但希望以上内容会让你指出正确的方向!