使用MongoDB Java驱动程序更新嵌入式文档中的字段? [英] Updating fields in embedded documents with MongoDB Java Driver?
问题描述
我正在尝试使用Java驱动程序对MongoDB中的嵌入式文档进行更新,但收到一个IllegalArgumentException异常,该异常指出存储在db中的字段中不能包含."
I'm trying to perform an update on an embedded document in MongoDB with the Java driver but receive an IllegalArgumentException that states "fields stored in the db can't have . in them"
我的文档具有以下结构:
My document has the structure:
{
"_id" : ObjectId("5155d102a47d7b00b7e4bed2"),
"foo" : {
"bar" : {
"name" : "Now"
}
}
}
我想执行这样的更新
var query = {_id:ObjectId("5155d102a47d7b00b7e4bed2")};
var update = {"foo.bar.time":new Date()};
var withSet = {$set:update};
db.samples.update(query,withSet);
从控制台正确修改文档的
which from the console correctly modifies the document
{
"_id" : ObjectId("5155d102a47d7b00b7e4bed2"),
"foo" : {
"bar" : {
"name" : "Now",
"time" : ISODate("2013-03-29T18:02:51.591Z")
}
}
}
尝试在Java中做同样的事情我没有成功.我已经尝试过了:
Trying to do the same in Java I have not been successful. I've tried this:
BasicDBObject query = new BasicDBObject("_id", new ObjectId("5155d102a47d7b00b7e4bed2"));
BasicDBObject time = new BasicDBObject("time", new Date());
BasicDBObject bar = new BasicDBObject("bar", time);
BasicDBObject foo = new BasicDBObject("foo", bar);
BasicDBObject withSet = new BasicDBObject("$set", foo);
samples.update(query, withSet);
但是它掩盖了嵌入的bar对象,破坏了名称.
But it clobbers the embedded bar object, destroying name.
我也尝试过:
BasicDBObject foo = new BasicDBObject();
foo.append("foo.bar.time", new Date());
samples.update(query, foo)
但是会收到一个IllegalArgumentException.
But receive an IllegalArgumentException.
我看到了在Stack Overflow上选择的其他答案,其中包括该点符号.有什么我想念的吗?在嵌入式文档中更新字段的正确方法是什么?
I've seen other answers chosen on Stack Overflow that include this dot notation. Is there something I'm missing? What is the proper way to update a field in an embedded document?
推荐答案
在您的最后一个示例中,缺少了$set
部分,这可能会导致问题.尝试
In your last example the $set
part is missing, maybe this causes the problem. Try
samples.update(
query,
new BasicDBObject(
"$set",
new BasicDBObject("foo.bar.time", new Date())
));
相反.
这篇关于使用MongoDB Java驱动程序更新嵌入式文档中的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!