douhao8456
2019-04-30 12:34
浏览 430

在Mongo-go-driver中创建一个唯一字段

I am very new to both Go and Mongodb and was writing my first rest-api with Go and Mongo. I am using mongo-go-driver and have the following Modal struct in Go

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.

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.

So is there a way I can do this.

图片转代码服务由CSDN问答提供 功能建议

我对Go和Mongodb都很陌生,并且正在用Go和Mongo编写我的第一个rest-api。 我正在使用 mongo-go-driver 并在Go中具有以下 Modal 结构

  type Modal struct {
 组[] string`bson:“ group” json:“ group”`
主机名字符串`bson:“ hostname” json:“ hostname”`
覆盖map [string] string`bson:“ overrides” json:“ overrides  “`
排除[]字符串`bson:”排除“ json:”排除“`
} 
   
 
 

我不想使用默认的 ObjectId 字段作为我的主键,而想将 Hostname 字段作为主键。

Hostname 字段的类型设置为 primitive.ObjectID ,则 hostname 将是唯一的,但是其值将由mongodb随机生成,而不是 实际的主机名字符串值。

所以有办法吗?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongtui2029 2019-04-30 12:43
    已采纳

    You may use a unique index to enforce / allow only distinct values of a given field, e.g.:

    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:

    indexName, err := coll.Indexes().CreateOne(
        context.Background(),
        IndexModel{
            Keys   : bsonx.Doc{{"hostname", bsonx.Int32(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). If this doesn't bother you, you're done.

    Also note that you may map Modal.Hostname to the _id field with struct tags:

    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.

    点赞 打赏 评论

相关推荐 更多相似问题