[英]how can I avoid duplicating documents in Mongodb using c#
I try to avoid duplicate documents in MongoDB database using asp.net mvc . 我尝试使用asp.net mvc避免MongoDB数据库中的重复文档。 I used an objectID generated manually but I still get duplicate documents. 我使用了手动生成的objectID,但仍然得到了重复的文档。
this is my code 这是我的代码
//collection "Devise1"
public class Devise
{
public ObjectId id_devise { get; set; }
public string parité { get; set; }
public float low { get; set; }
public float high { get; set; }
public string date_observation_d { get; set; }
}
//code insertion
System.IO.StreamReader file = new System.IO.StreamReader(@"C:\Users\user PC\Desktop\données financiere finale\Classeur1.csv");
string fileLines;
try {
while ((fileLines = file.ReadLine()) != null)
{
string[] elements;
elements = fileLines.Split(new char[] { ' ' });
for (int x = 0; x < elements.Length; x++)
{
devises2.parité = "EUR/USD";
devises2.id_devise = new ObjectId();
devises2.date_observation_d = elements[0];
devises2.low = float.Parse(elements[3], CultureInfo.InvariantCulture.NumberFormat);
devises2.high = float.Parse(elements[2], CultureInfo.InvariantCulture.NumberFormat);
collection1.InsertOneAsync(devises2);
}
}
}
catch(Exception ex)
{
throw ex;
}
Create unique index on id_devise
in your collection. 在集合中的id_devise
上创建唯一索引。
You can create index in your C# application but simple approach will be to run this in your MongoDB shell. 您可以在C#应用程序中创建索引,但是简单的方法是在MongoDB Shell中运行该索引。 See Create Unique Index in MongoDB documentation. 请参阅MongoDB文档中的创建唯一索引 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.