C# MongoDbDriver 插入不存在的元素
考虑以下条目的数组:
Public Class Potato
{
string Attribute_1 { get; set }
decimal Attribute_2 { get; set; }
DateTimeOffset Attribute_3 { get; set; }
}
仅插入集合中尚未存在的元素(通过使用所有 3 个属性的复合键)的最简洁方法是什么?
目前我正在一项一项地进行,但它可能不是最佳的(并且可能应该使用事务?):
foreach (var newEntry in newEntries)
{
var builder = Builders<Potato>.Filter;
var filter = builder.Eq(r => r.Attribute_1, newEntry.Attribute_1)
& builder.Eq(r => r.Attribute_2, newEntry.Attribute_2)
& builder.Eq(r => r.Attribute_3, newEntry.Attribute_3);
var cursor = await _collection.FindAsync(filter);
if (await cursor.AnyAsync())
{
return 0;
}
await _collection.InsertOneAsync(newEntry);
return 1;
}
Consider an array of the following entries:
Public Class Potato
{
string Attribute_1 { get; set }
decimal Attribute_2 { get; set; }
DateTimeOffset Attribute_3 { get; set; }
}
What would be the most concise way to insert only those elements that are not already in the collection (by composite key using all 3 attributes)?
Currently I'm doing it one by one, but it might not be optimal (and probably should use a transaction?):
foreach (var newEntry in newEntries)
{
var builder = Builders<Potato>.Filter;
var filter = builder.Eq(r => r.Attribute_1, newEntry.Attribute_1)
& builder.Eq(r => r.Attribute_2, newEntry.Attribute_2)
& builder.Eq(r => r.Attribute_3, newEntry.Attribute_3);
var cursor = await _collection.FindAsync(filter);
if (await cursor.AnyAsync())
{
return 0;
}
await _collection.InsertOneAsync(newEntry);
return 1;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用约束可能是一个好方法。
如果我没记错的话,这正是约束存在的原因。为什么你不喜欢使用索引?
https://www.mongodb.com/docs/manual/core/index -独特/
Using constraints is might be a good way.
If I don't know wrong, this is exactly what constraints exist for. Why don't you prefer to use indexes?
https://www.mongodb.com/docs/manual/core/index-unique/