[英]Making a unique field in Mongo-go-driver
I am very new to both Go and Mongodb and was writing my first rest-api with Go and Mongo.我对 Go 和 Mongodb 都很陌生,并且正在用 Go 和 Mongo 编写我的第一个 rest-api。 I am using
mongo-go-driver
and have the following Modal
struct in Go我正在使用
mongo-go-driver
并在 Go 中具有以下Modal
结构
type Modal struct {
Group []string `bson:"group" json:"group"`
Hostname string `bson:"hostname" json:"hostname"`
Overrides map[string]string `bson:"overrides" json:"overrides"`
Excludes []string `bson:"excludes" json:"excludes"`
}
I do not want to use the default ObjectId
field provided by mongo-db as my primary key and instead would like to make the Hostname
field as the primary key.我不想使用 mongo-db 提供的默认
ObjectId
字段作为我的主键,而是希望将Hostname
字段作为主键。
If I make the type of Hostname
field as primitive.ObjectID
, then the hostname
would be unique but its value will be randomly generated string by mongodb and not the actual hostname string value.如果我将
Hostname
字段的类型设为 original.ObjectID ,则hostname
名将是唯一的,但其值将由primitive.ObjectID
随机生成的字符串,而不是实际的主机名字符串值。
So is there a way I can do this.那么有没有办法我可以做到这一点。
You may use a unique index to enforce / allow only distinct values of a given field, eg:您可以使用唯一索引来强制/只允许给定字段的不同值,例如:
db.collectionname.createIndex( { "hostname": 1 }, { unique: true } )
If you want to create such index using the official MongoDB driver, this is how you can do that:如果您想使用官方 MongoDB 驱动程序创建此类索引,您可以这样做:
indexName, err := coll.Indexes().CreateOne(
context.Background(),
mongo.IndexModel{
Keys: bson.D{{Key: "hostname", Value: 1}},
Options: options.Index().SetUnique(true),
},
)
But know that in MongoDB each document must have an _id
property, so doing the above, documents will have an auto-generated _id
field (of ObjectId
type).但是要知道在 MongoDB 中每个文档都必须有一个
_id
属性,因此执行上述操作,文档将具有一个自动生成的_id
字段( ObjectId
类型)。 If this doesn't bother you, you're done.如果这不打扰你,你就完成了。
Also note that you may map Modal.Hostname
to the _id
field with struct tags:另请注意,您可以使用结构标记将
Modal.Hostname
映射到_id
字段:
type Modal struct {
Group []string `bson:"group" json:"group"`
Hostname string `bson:"_id" json:"hostname"`
Overrides map[string]string `bson:"overrides" json:"overrides"`
Excludes []string `bson:"excludes" json:"excludes"`
}
And again, you're done.再一次,你完成了。 The downside of this solution is that the documents in MongoDB will not have a property named
hostname
, as it will be stored in _id
.此解决方案的缺点是 MongoDB 中的文档没有名为
hostname
的属性,因为它将存储在_id
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.