【问题标题】:Insert a mgo query []M.bson result into a file.txt as a string将 mgo 查询 []M.bson 结果作为字符串插入到 file.txt
【发布时间】:2018-10-19 09:26:38
【问题描述】:

我必须将mgo query MongoDB 转换为Go 的结果插入到文件中以获得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 但它让我在每个结果的最后一个得到枚举排序值

我想放弃那些012345

    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")

【问题讨论】:

    标签: string mongodb go bson mgo


    【解决方案1】:

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

    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()
    

    【讨论】:

    • 请问oneEntry 是干什么用的??我不明白
    • 现在修复了,我的错误,StackOverflow linter 没有正常工作,或者根本没有。
    猜你喜欢
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 2013-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多