Aarthi Chandrasekaran
Aarthi Chandrasekaran

Reputation: 589

How to update a mongodb collection using C#

I have a mongo server having a collection states. whenever a new state is adding it is save in my server. But when i try to edit the collection in front end it is saved as another new collection in my server with different id. how to overcome this.

     public  static void CreateData(string pass ,string pass1)
      {

          string StateCode = pass;
          string stateName = pass1;
          insertState(StateCode, stateName);

      }



      private static void insertState(string StateCode, string stateName)
      {
        MongoServer server = MongoServer.Create(ConnectionString);
        MongoDatabase myCompany = server.GetDatabase("BackOffice");

        MongoCollection<BsonDocument> tblStates = myCompany.GetCollection<BsonDocument>("tblStates");
        BsonDocument deptartment = new BsonDocument {
                    { "State_strCode", StateCode },
                    { "State_strName", stateName },
                    {"States_strIsActive","Y"},
                    {"State_strFedExStateCode",""},
                    {"State_dtmTimeStamp",DateTime.Now}
                    };
        tblStates.Insert(deptartment);
       }

Upvotes: 0

Views: 148

Answers (1)

Eugene
Eugene

Reputation: 325

You'd better define a structure or set a PK:

public class Customer
{
    public string name { get; set; }
    [MongoDB.Bson.Serialization.Attributes.BsonId]
    public string idCol { get; set; }
}

and update your object like this

 public void Update(Customer cus)
    {
        if (cus != null)
        {
            MongoDB.Driver.MongoClient client = new MongoClient(_connectionString);
            MongoDatabase db = client.GetServer().GetDatabase(_dbName);
            db.GetCollection(_dbName).Save(cus);
        }

    }

Upvotes: 1

Related Questions