将地图转换为bson

时间:2018-03-01 04:27:58

标签: go mgo

type Player struct {
    id bson.ObjectId
    test map[int]int
}

func (this *Player) Id() bson.ObjectId {
    return this.id
}

func (this *Player) DbObj() bson.D {

    testBson := bson.D{}
    for k,v := range this.test {
        testBson = append(testBson, bson.M{"id":k, "v":v}) // compile error
    }
    return bson.D{
        {"_id",this.id},
        {"test", testBson},
    }
}

bson文件应该是:

{'_id':ObjectId(xx),'test':[{'id':1,'v':1},..., {'id':2,'v':2}]}

但我不知道如何将地图对象转换为[{'id':1,'v':1},..., {'id':2,'v':2}],bson.M不是D包含的DocElem类型

1 个答案:

答案 0 :(得分:1)

使用Go切片表示BSON数组:

func (this *Player) DbObj() bson.D {
    var testBson []bson.M
    for k,v := range this.test {
        testBson = append(testBson, bson.M{"id":k, "v":v}) 
    }
    return bson.D{
        {"_id",this.id},
        {"test", testBson},
    }
}