Home > OS >  How to find maximum value of a field in mongodb golang?
How to find maximum value of a field in mongodb golang?

Time:07-02

This is my code. I always get maximum value of 999, even when there are more blocks (e.g 3000 blocks).

This is what the document(s) look like.

enter image description here


func GetLatestBlockFromMongoDB() int{
    if contains(ReturnBlocksExists(), "blocks") == true {
        ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
        var blockheights []models.Block
        defer cancel()
    
        options := options.Find().SetProjection(bson.M{"block.header.blockNumber": 1})

        options.SetSort(bson.D{{"block.header.blockNumber", -1}})

        options.SetLimit(1)
    
        results, err := blocksCollections.Find(context.TODO(), bson.D{}, options)
    
        if err != nil {
            fmt.Println(err)
        }
    
        //reading from the db in an optimal way
        defer results.Close(ctx)
        for results.Next(ctx) {
            var singleBlock models.Block
            if err = results.Decode(&singleBlock); err != nil {
                fmt.Println(err)
            }
    
            blockheights = append(blockheights, singleBlock)
        }
        fmt.Println("%v", blockheights[0].Block.Header.BlockNumber)
        if len(strings.TrimSpace(blockheights[0].Block.Header.BlockNumber)) > 0{
            i, err := strconv.Atoi(blockheights[0].Block.Header.BlockNumber)
            if err != nil {
                glog.Fatalf("%v", err)
            }
            return i
        } else {
            return 0
        }
    } else {
        return 0
    }
}

How can i get the maximum value of blockNumber? I think the problem might be because blockNumber is a string but not an integer. I'm not sure. I did set sort and also limit 1 so it should normally work.

CodePudding user response:

Yes, you are right, from the image, I can see that the blockNumber field is a string, so you are not comparing integers, you are comparing string, where "999" is greater than "3000":

For example:

package main

import (
    "fmt"
)

func findMax(a []string) string {
    m := a[0]
    for _, value := range a {
        if value > m {
            m = value
        }
    }
    return m
}

func main() {
    blocks := []string{"999", "2000", "3000"}
    ma := findMax(blocks)
    fmt.Println(ma)
}
$ go run .
999

Check out this question too.

  • Related