当前位置: 首页 > 知识库问答 >
问题:

MongoDB如何插入批量文档并忽略重复文档

仇正豪
2023-03-14

我想插入一批文档,其中一些已经存在于集合中。所以我想要的是忽略它们,或者对我来说更好的解决方案是在例外情况下,我想记录哪个文档是重复的,如果可能的话,继续插入下一个文档。

我看到了几个类似的问题,但没有一个解决了这个问题。

我的代码如下所示:

        const string connectionString = "mongodb://127.0.0.1/localdb";

        var client = new MongoClient(connectionString);

        _database = client.GetDatabase("localdb");

        var collection = _database.GetCollection<BsonDocument>("Sales");


StringBuilder customValue;

        foreach (var data in dataCollectionDict)
        {
            customValue = new StringBuilder();

            customValue.Append(data["col1"]);
            customValue.Append(data["col2"]);
            customValue.Append(data["col3"]);
            customValue.Append(data["col4"]);
            customValue.Append(data["col5"]);
            customValue.Append(data["col6"]);

            data.AddRange(new BsonDocument("HashMultipleKey", SHA256Func(customValue.ToString())));
        }


await collection.Indexes.CreateOneAsync(new BsonDocument("HashMultipleKey", 1), new CreateIndexOptions() { Unique = true, Sparse = true ,});


await collection.InsertManyAsync(dataCollectionDict);

任何帮助都将不胜感激。

共有1个答案

锺离俊雄
2023-03-14

这是我发现的工作,我不确定这是否是最好的解决方案,我很想听听你是否有更好的方法。

      try
        {
            await collection.InsertManyAsync(dataCollectionDict);
        }
        catch (Exception ex)
        {
            ApplicationInsights.Instance.TrackException(ex);

            InsertSingleDocuments(dataCollectionDict,collection, dataCollectionQueueMessage);
        }
    }

    private static void InsertSingleDocuments(List<BsonDocument> dataCollectionDict, IMongoCollection<BsonDocument> collection
        ,DataCollectionQueueMessage dataCollectionQueueMessage)
    {
        ApplicationInsights.Instance.TrackEvent("About to start insert individual docuemnts and to find the duplicate one");

        foreach (var data in dataCollectionDict)
        {
            try
            {
                collection.InsertOne(data);
            }
            catch (Exception ex)
            {
                ApplicationInsights.Instance.TrackException(ex,new Dictionary<string, string>() {
                    {
                        "Error Message","Duplicate document was detected, therefore ignoring this document and continuing to insert the next docuemnt"
                    }, {
                        "FilePath",dataCollectionQueueMessage.FilePath
                    }}
                );
            }
        }
    }
 类似资料:
  • 主要内容:insert() 与 save() 方法,insertOne() 方法,insertMany() 方法前面我们已经介绍了如何在 MongoDB 中 创建数据库和 创建集合,接下来我们再来介绍一下如何在集合中插入文档。文档是 MongoDB 中数据的基本单位,由 BSON 格式(一种计算机数据交换格式,类似于 JSON)的键/值对组成。 insert() 与 save() 方法 您可以使用 MongoDB 中的 insert() 或 save() 方法向集合中插入文档,语法如下: db.

  • 问题内容: TLDR;如何批量格式化JSON文件以提取到Elasticsearch? 我试图将一些NOAA数据吸收到Elasticsearch中,并一直在利用NOAAPythonSDK。 我编写了以下Python脚本来加载数据并以JSON格式存储。 JSON输出: 该脚本解决了我遇到的一些格式化问题,我的下一个障碍是尝试对其进行格式化,以便可以在elasticsearch中利用批量导入功能。我偶然

  • 问题内容: 我在使用mgo将mongodb中保留golang结构时遇到问题。 问题是,在完成Insert()调用后,唯一保留在数据库中的是空文档 我检查struct字段是否确实已设置,并且不为空。关于为什么这样的任何想法。提示表示赞赏:)谢谢 问题答案: 您需要通过以大写字母开头的字段名称来导出字段。

  • 问题内容: 我正在使用PHP。 请问什么是将新记录插入具有唯一字段的数据库的正确方法。我正在批量插入很多记录,我只想插入新记录,并且我不想重复条目有任何错误。 有没有唯一方法可以首先进行SELECT并查看条目是否在INSERT之前已经存在-并且仅在SELECT不返回任何记录时才插入INSERT?我希望不是。 我想以某种方式告诉MySQL忽略这些插入而没有任何错误。 谢谢 问题答案: 如果在重复记录

  • 我有一个具有以下模式的用户集合: 用户将查找用户。名称,必须是唯一的。添加新用户时,我首先执行搜索,如果没有找到这样的用户,我会将新用户文档添加到集合中。搜索用户和添加新用户(如果未找到)的操作不是原子操作,因此,当多个应用程序服务器连接到DB服务器时,可能会同时收到两个具有相同用户名的添加用户请求,从而导致两个添加用户请求都找不到这样的用户,这反过来会导致两个文档具有相同的“user.name”

  • 我想知道是否有一种方法可以插入新文档并一次返回。 这是我目前使用的: