简体   繁体   中英

c# mongodb BsonDocument array

the below code seems to work except that the values are not actually saved to the existing document.

    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));

I say it works because this the result of getlasterror run immediately after the save:

db.GetLastError()
{MongoDB.Driver.GetLastErrorResult}
base {MongoDB.Driver.CommandResult}: {MongoDB.Driver.GetLastErrorResult}
DocumentsAffected: 1
HasLastErrorMessage: false
LastErrorMessage: null
UpdatedExisting: true

I'm missing something (probably something simple...). Thanks for any assistance.

The code works fine (well, with a few tweaks to make it compile standalone and to fit my test environment):

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));
}

Test:

> 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" } ] }

FYI: RequestStart returns an IDisposable object. I'm not sure why you're trying to use it, but you're using it incorrectly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM