下面的代码似乎有效,除了这些值实际上没有保存到现有文档中。
MongoServer mongo = MongoServer.Create();
mongo.Connect();
var db = mongo.GetDatabase("forms");
mongo.RequestStart(db);
var collection = db.GetCollection("forms");
var query = new QueryDocument("_id",ObjectId.Parse(Id));
var resultsCursor = collection.Find(query);
foreach (BsonDocument item in resultsCursor)
{
var formFields = new BsonArray();
formFields.Add(new BsonDocument
{
{"ID", ObjectId.GenerateNewId()},
{"NAME",name},
{"TYPE",type}
}
);
collection.Save(item.Add("fields",formFields));
我说它有效,因为getlasterror的结果在保存后立即运行:
db.GetLastError()
{MongoDB.Driver.GetLastErrorResult}
base {MongoDB.Driver.CommandResult}: {MongoDB.Driver.GetLastErrorResult}
DocumentsAffected: 1
HasLastErrorMessage: false
LastErrorMessage: null
UpdatedExisting: true
我错过了一些东西(可能是简单的......)。 感谢您的帮助。
答案 0 :(得分:1)
代码工作正常(好吧,通过一些调整使其独立编译并适合我的测试环境):
MongoServer mongo = MongoServer.Create();
mongo.Connect();
var db = mongo.GetDatabase("test");
// mongo.RequestStart(db); // removed as it's not correct
var collection = db.GetCollection("so");
var query = new QueryDocument("_id", "12345"); // hard-coded an ID for test
var resultsCursor = collection.Find(query);
foreach (BsonDocument item in resultsCursor)
{
var formFields = new BsonArray();
formFields.Add(new BsonDocument
{
{"ID", ObjectId.GenerateNewId()},
{"NAME", item["Name"].AsString}, // grabbed a few values from doc
{"TYPE", item["Type"].AsString} // to move into an array
});
collection.Save(item.Add("fields", formFields));
}
测试:
> db.so.remove()
> db.so.insert({_id: "12345", Name: "Jon Smith", Type: "Employee"})
> db.so.find()
{ "_id" : "12345", "Name" : "Jon Smith", "Type" : "Employee" }
> // Ran application here
> db.so.find()
{ "_id" : "12345", "Name" : "Jon Smith", "Type" : "Employee",
"fields" : [{"ID" : ObjectId("52039e395bddbf23f8cc0888"),
"NAME" : "Jon Smith",
"TYPE" : "Employee" } ] }
仅供参考:RequestStart
返回IDisposable
个对象。我不确定你为什么要尝试使用它,但是你没有错误地使用它。