I've just started working with MongoDB for c# and I'm trying to upsert some documents in a collection. I'm using the 'save' command (and even tried update with upsert flag on) but every time I run my code it keeps inserting duplicates: the new records have new object ids (randomly generated) but all the rest of the data is the same. What am I doing wrong? Any suggestion is greatly appreciated.
Here's my code:
List<LatestDataReduced> latestdata = new List<LatestDataReduced>();
//LatestDataReduced is the model of my documents
foreach (var dep in lrd)
{
foreach (var rec in dep.record)
{
var entity = new LatestDataReduced();
entity.PlatformID = platid;
//fill up data in entity...
latestdata.Add(entity);
}
}
var connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
var server = client.GetServer();
var database = server.GetDatabase("emodnet2");
var collection = database.GetCollection<LatestDataReduced>("latestdata");
foreach (var ld in latestdata)
{
/*var query = Query.And(Query.EQ("Id", ld.Id), Query.EQ("Date", ld.Date), Query.EQ("Depth", ld.Depth), Query.EQ("PlatformID", ld.PlatformID), Query.EQ("Pressure", ld.Pressure));
var update = Update.Replace(ld);
collection.Update(query, update, UpdateFlags.Upsert);*/
collection.Save(ld);
}
LatestDataReduced class:
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MongoDB.Models
{
public class CodeValuePair
{
public string Code { get; set; }
public double Value { get; set; }
}
public class LatestDataReduced
{
//[BsonIgnoreIfDefault]
public ObjectId Id { get; set; }
public int PlatformID { get; set; }
public DateTime Date { get; set; }
public double Depth { get; set; }
public List<CodeValuePair> ParamValue { get; set; }
public double Pressure { get; set; }
public List<CodeValuePair> ParamValueInfo { get; set; }
public string Roos { get; set; }
}
}
LatestDataReduced? If yourLatestDataReducedclass defines anIdproperty, then Mongo should be using that as the_idvalue in the saved docs.