简体   繁体   English

如何避免使用c#在Mongodb中复制文档

[英]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.

相关问题 如何从 c# 计算 mongodb 中带有过滤器的文档 - How do I count documents with a filter in mongodb from c# 如何使用 c# 在 mongodb 中批量插入文档(大小为 10) - How to insert documents in batches (Size of 10) in mongodb using c# MongoDb:使用和C#实现具有可变结构的文档 - MongoDb: documents with variable structure using and C# 如何避免C#中的StackOverflowException? - How can I avoid a StackOverflowException in C#? 如何使用C#.Net将文档保存到Lotus Quickr? - How can I save documents to Lotus Quickr using C# .Net? 如何使用C#访问iOS App的Documents文件夹 - How can I access Documents folder of iOS App with C# 如何在C#中使用ObjectId中的时间戳过滤文档? - How do I filter documents using the timestamp in ObjectId in C#? 如何使用MongoDB和C#使用另一个字段的值更新文档? - How to update documents using another field's value using MongoDB and C#? 使用c#excel introp将多个工作表添加到工作簿中时,如何避免COMException? - How can i avoid COMException while adding multiple worksheets into a workbook using c# excel introp ? 如何使C#“使用”别名公开,以避免“不一致的可访问性”错误? - How can I make a C# “using” alias public to avoid “inconsistent accessibility” errors?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM