I am using mongodb driver, insert worked with no problem, but that will lead me with multiple documents with the same ID.
What I´m trying to do it´s to use UpdateOne with upsert, to update my document if the ID is found, or just insert if there´s no found ID.
I´m working with MongoDB.Driver 2.8.1, using NET framework 4.5, I read some documentation an examples in differents forums about my issue but can´t fix it.
Here´s the part of the code where I´m having problems.
{
var client = new MongoClient(getMongoConect());
var database = client.GetDatabase("Example");
var collection = database.GetCollection<BsonDocument>("Data");
var upsert = new UpdateOptions { IsUpsert = true };
var variables = new BsonDocument
{
{"op_id", transaction.ID },
{"op_box", transaction.Operation},
{"RegisterDate",transaction.TodayDate },
{"ProcedureKind",transaction.Procedure},
{"User",transaction.RegisterUser },
{"Status", transaction.ProcedureStatus},
{"Ofice", transaction.OficeNumber }
};
var filter = Builders<BsonDocument>.Filter.Eq("op_id", transaction.ID);
var update = Builders<BsonDocument>.Update.Set("op_id", transaction.ID);
var object= collection.Find(filter);
//Works with no problems, but give me trash at the DB.
//collection.InsertOne(variables);
//Trying to update document if op_id exist or insert if not
collection.UpdateOne(filter,update,upsert);
}
I expect the Collection.UpdateOne to save the whole document if the id is not found and update it if it is.
here's how i would do it for upserting whole documents. code also shows how to update only certain fields of existing documents.
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
namespace StackOverflow
{
public class Program
{
public class Data
{
[BsonId]
public ObjectId op_id { get; set; }
public string op_box { get; set; }
public string office { get; set; }
}
private static void Main(string[] args)
{
var collection = new MongoClient("mongodb://localhost:27017")
.GetDatabase("Example")
.GetCollection<Data>("Data");
var id = ObjectId.GenerateNewId();
//use ReplaceOne when you are inserting or updating whole documents
collection.ReplaceOne(
d => d.op_id == id,
new Data
{
op_id = id,
op_box = "box",
office = "office"
},
new UpdateOptions
{
IsUpsert = true
});
//use UpdateOne when you need to update only a few properties/fields
collection.UpdateOne(
d => d.op_id == id,
Builders<Data>.Update.Set(d => d.office, "updated office"));
}
}
}
i've written a library that simplifies much of this. check it out if you are able to use .net core framework. with it you can simply do object.Save()
and it'll take care of upserting.