【问题标题】:Make an Array of unique elements in c# mongodb driver在 c# mongodb 驱动程序中创建一个唯一元素数组
【发布时间】:2020-02-20 23:02:06
【问题描述】:

如何在 MongoDB c# 驱动程序中创建唯一元素数组,

我不想每次都检查这个元素是否已经在数组中。

假设:

list=[1,2,3,4]

那么我应该不能添加重复元素(例如3

【问题讨论】:

  • 我假设您指的是插入时的唯一性?如果是这样,请查看唯一索引选项。
  • 我希望插入和更新的唯一性。如何在 MongoDB c# 驱动程序中为数组元素创建唯一索引
  • HI @akash - 索引是在数据库上创建的。我怀疑您可以通过 c# 驱动程序发出命令,但是再次创建索引通常不会多次执行。考虑到这一点,您可能会发现使用 mongo shell 创建索引更容易。这是文档...docs.mongodb.com/manual/reference/method/…
  • @barrypicker - 如果我在数据库上创建索引,那么我认为数组将是唯一的,而不是数组中的元素。
  • 这篇文章应该给你一个良好的开端stackoverflow.com/a/43052168/1859959。我的意思是“但如果你严格使用 $addToSet 和索引”部分

标签: c# mongodb .net-core


【解决方案1】:

您可以在每次创建或更新数组时使用AddToSetAddToSetEach 方法,如 cmets 中所述:

var update = Builders<Entity>.Update.AddToSetEach(e => e.Items, new [] {1, 2});
collection.UpdateOne(new BsonDocument(), update, new UpdateOptions { IsUpsert = true });

您可以在创建集合时定义schema validation,以确保永远不会允许重复的项目(插入/更新时会抛出错误,“文档验证失败”)。

您可以在 MongoDB shell 中定义模式,或者这里是如何在 C# 中进行:

var options = new CreateCollectionOptions<Entity>
{
    ValidationAction = DocumentValidationAction.Error,
    ValidationLevel = DocumentValidationLevel.Strict,
    Validator = new FilterDefinitionBuilder<Entity>().JsonSchema(new BsonDocument
    {
        { "bsonType", "object" },
        { "properties", new BsonDocument("Items", new BsonDocument
            {
                { "type" , "array" },
                { "uniqueItems", true }
            })
        }
    })
};

database.CreateCollection("entities", options, CancellationToken.None);

Entity 是这样的示例类:

public class Entity
{
    public ObjectId Id { get; set; }
    public int[] Items { get; set; }
}

这里是API docs for CreateCollectionOptions,在单元测试中你可以看到examples of usage - e.g. JsonSchema()。不幸的是,我在参考文档中没有看到任何更详尽的解释。

【讨论】:

  • 能分享一下mongodb c# driver validation schema docs的链接吗??
  • 添加链接 - 单元测试似乎是最好的文档
猜你喜欢
  • 2017-07-02
  • 2019-04-08
  • 1970-01-01
  • 1970-01-01
  • 2016-09-11
  • 2014-09-14
  • 1970-01-01
  • 2018-12-17
  • 1970-01-01
相关资源
最近更新 更多