将 mgo 查询 []M.bson 结果作为字符串插入 file.txt

Insert a mgo query []M.bson result into a file.txt as a string

我必须将 mgo query MongoDBGo 中转换的结果插入到文件中以获得 the id of images

 var path="/home/Medo/text.txt"

   pipe := cc.Pipe([]bson.M{
              {"$unwind": "$images"}, 
              {"$group": bson.M{"_id": "null", "images":bson.M{"$push": "$images"}}},

              {"$project": bson.M{"_id": 0}}})

    response := []bson.M{}
    errResponse := pipe.All(&response)
    if errResponse != nil {
        fmt.Println("error Response: ",errResponse)
    }
    fmt.Println(response) // to print for making sure that it is working 

    data, err := bson.Marshal(&response)
    s:=string(data)

    if err22 != nil {
        fmt.Println("error insertion ", err22)
    } 

这是我必须创建文件并在其上写入的部分。

问题是当我在文本文件中得到查询结果时,我在每个值的最后得到一个枚举值,例如:

id of images 
23456678`0`
24578689`1`
23678654`2`
12890762`3`
76543890`4`
64744848`5`

所以对于每个值,我在最后得到一个排序的数字,但我不知道如何在从查询中获得响应后将 Bson 转换为 []Byte 然后String但它让我在每个结果的最后得到枚举排序值

我想放弃那些 0 1 2 3 4 5

    var _, errExistFile = os.Stat(path)

    if os.IsNotExist(errExistFile) {
        var file, errCreateFile = os.Create(path)
        if isError(erro) {
            return
        }
        defer file.Close()
    }

    fmt.Println("==> done creating file", path)
    var file, errii = os.OpenFile(path, os.O_RDWR, 0644)
    if isError(errii) {
        return
    }
    defer file.Close()

    // write some text line-by-line to file
    _, erri := file.WriteString(s)
    if isError(erri) {
        return
    }

    erri = file.Sync()
    if isError(erri) {
        return
    }

    fmt.Println("==> done writing to file")

您可以声明一个简单的结构,例如

simple struct {
  ID    idtype `bson:"_id"`
  Image int    `bson:"images"`
}

将图像 ID 放入文件的函数是

open file stuff…

result := simple{}
iter := collection.Find(nil).Iter()
for iter.Next(&result){
 file.WriteString(fmt.Sprintf("%d\n",result.Image))
}
iter.Close()