douhao8456 2019-04-30 12:34
浏览 666
已采纳

在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.

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用