将地图转换为 bson

convert map to bson

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

使用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},
    }
}