0

下面的代码似乎有效,只是这些值并未实际保存到现有文档中。

    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

我错过了一些东西(可能是一些简单的东西......)。感谢您提供任何帮助。

4

1 回答 1

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对象。我不确定您为什么要尝试使用它,但是您使用不正确。

于 2013-08-08T13:36:47.107 回答