database - 仅当字段不为空时才将字段设置为索引
问题描述
我有一个带有两个键的结构,如下所示:
{
"cannot_be_empty": "hello",
"can_be_empty": "world"
}
现在我将索引设置为can_be_empty
和的组合cannot_be_empty
。
db.collection.Indexes.CreateOne(IndexModel{{Keys: bson.D{
{Key: "cannot_be_empty", Value: 1},
{Key: "can_be_empty", Value: 1},
}})
但是,我想让它can_be_empty
在所有字段中都必须是唯一的,除非它是一个空字符串。有没有办法做到这一点?我认为https://docs.mongodb.com/manual/core/index-partial/可能是要走的路,但我不太确定它是如何工作的。
谢谢!
更新:我发现这$ne
不起作用,所以我尝试了这个,目前我的测试仍然失败,但我会尝试找出原因。
// Set partial index option
myPartialIndex := options.Index().SetPartialFilterExpression(bson.D{{
Key: "can_be_empty",
Value: bson.D{{Key: "$gt", Value: ""}},
}})
// Set up all indexes
indexes := []mongo.IndexModel{
{Keys: bson.D{{Key: "cannot_be_empty", Value: 1}, {Key: "can_be_empty", Value: 1}}},
{Keys: bson.D{{Key: "can_be_empty", Value: 1}}, Options: myPartialIndex},
}
// Create index, no error
db.collection.Indexes().CreateMany(ctx, indexes)
更新 2:我不知道我必须添加一个独特的选项才能工作。无论如何,我还需要can_be_empty
and的复合键cannot_be_empty
是唯一的。
最后更新:我已经接受了答案,但也会发布我自己的 Golang 版本。
myUniqueIndex := options.Index().SetUnique(true)
myPartialIndex := options.Index().SetPartialFilterExpression(bson.D{{
Key: "can_be_empty",
Value: bson.D{{Key: "$gt", Value: ""}},
}})
// Set up all indexes
indexes := []mongo.IndexModel{
{Keys: bson.D{{Key: "cannot_be_empty", Value: 1}, {Key: "can_be_empty", Value: 1}}, Options: myUniqueIndex},
{Keys: bson.D{{Key: "can_be_empty", Value: 1}}, Options: myPartialIndex},
}
// Create index, no error
db.collection.Indexes().CreateMany(ctx, indexes)
解决方案
你可以使用$gt
空字符串。
db.collection.createIndex(
{ can_be_empty: 1, cannot_be_empty: 1 },
{ unique: true, partialFilterExpression: { "can_be_empty": { "$gt": "" } } }
)
推荐阅读
- reactjs - 如何将 EsLint 与 Vite+react 项目集成
- ckeditor - 在 PHP 应用程序上安装 CKEditor 会给出非标准字符,其他问题
- virtualbox - 让主机使用访客互联网连接
- c# - 我需要在 csharp 中每 1 秒向我的 var 添加 1 而无需停止程序
- ffmpeg - FFmpeg 自定义构建支持将 .ts 转换为 .mp4 文件
- google-sheets - 谷歌表格中日期和小时的 Unix 时间戳
- python - 在 Flask 应用程序中显示某种等待状态指示器
- asp.net - 如何在 ASP.NET Webforms 中动态设置 HtmlTableCell 的值?
- c - 如何在 C 中的共享内存中使用动态大小
- ruby-on-rails - 与 Rails 6 和 minitest 并行运行测试时,文件操作相关测试失败