首页 > 解决方案 > 仅当字段不为空时才将字段设置为索引

问题描述

我有一个带有两个键的结构,如下所示:

{
    "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_emptyand的复合键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)

标签: databasemongodbgoindexingmongo-go

解决方案


你可以使用$gt空字符串。

db.collection.createIndex(
   { can_be_empty: 1, cannot_be_empty: 1 },
   { unique: true, partialFilterExpression: { "can_be_empty": {  "$gt": "" }  } }
)

推荐阅读