douzi9430 2018-05-09 09:50
浏览 51
已采纳

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

i have to insert into a file the result of a mgo query MongoDB converted in Go to get 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)
    } 

Here is the part where I have to create a file and write on it.

The problem is when I got the result of the query in the text file I got an enumeration values in the last of each value for example:

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

so for each value i got a number sorted in the last , and i can't figure out how , after getting the reponse from the query i converted the Bson to []Byte and then to Stringbut it keeps me getting that enumeration sorted values in the last of each results

I'd like to drop those 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")
  • 写回答

1条回答 默认 最新

  • doumei3828 2018-05-09 13:23
    关注

    You could declare a simple struct eg

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

    The function to put the image ids into the file would be

    open file stuff…
    
    result := simple{}
    iter := collection.Find(nil).Iter()
    for iter.Next(&result){
     file.WriteString(fmt.Sprintf("%d
    ",result.Image))
    }
    iter.Close()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图