I'm working on couchdb in golang, I need to select the record with limit 1, I'm trying with the below mango query.

{"selector": {"$and": [{"memid": {"$gt": "null"}}, {"custid": {"$gt": "null"}}]},"limit" : 1}

The above query works well and good in fauxton on browser, but the same is not working in golang, all the results are coming without applying limit.

golang query:

queryString := fmt.Sprintf("{\"selector\": {\"$and\": [{\"memid\": {\"$gt\": \"%s\"}}, {\"custid\": {\"$gt\": \"%s\"}}]},\"limit\" : \"%d\"}", "null", "null",1)
queryResults, err := getQueryResultForQueryString(stub, queryString)

function definition for getQueryResultForQueryString:

func getQueryResultForQueryString(stub shim.ChaincodeStubInterface, queryString string) ([]byte, error) {

    fmt.Printf("- getQueryResultForQueryString queryString:\n%s\n", queryString)

    resultsIterator, err := stub.GetQueryResult(queryString)
    if err != nil {
        return nil, err
    }
    defer resultsIterator.Close()

    // buffer is a JSON array containing QueryRecords
    var buffer bytes.Buffer
    buffer.WriteString("[")

    bArrayMemberAlreadyWritten := false

    for resultsIterator.HasNext() {
        queryResponse, err := resultsIterator.Next()
        if err != nil {
            return nil, err
        }
        // Add a comma before array members, suppress it for the first array member
        if bArrayMemberAlreadyWritten == true {
            buffer.WriteString(",")
        }
        buffer.WriteString("{\"Key\":")
        buffer.WriteString("\"")
        buffer.WriteString(queryResponse.Key)
        buffer.WriteString("\"")

        buffer.WriteString(", \"Record\":")
        // Record is a JSON object, so we write as-is
        buffer.WriteString(string(queryResponse.Value))
        buffer.WriteString("}")
        bArrayMemberAlreadyWritten = true
    }
    buffer.WriteString("]")

    fmt.Printf("- getQueryResultForQueryString queryResult:\n%s\n", buffer.String())

    return buffer.Bytes(), nil
}
1 upvote
  flag
I would suggest using a proper CouchDB library for Go. Several are available. My preference is for Kivik, but I wrote it, so I'm biased. – Flimzy
1 upvote
  flag
But even if you don't want to use a proper CouchDB library, at least use proper JSON marshaling, rather than building a JSON string from scratch. – Flimzy

0 Answers 11

Not the answer you're looking for? Browse other questions tagged or ask your own question.