'Filter in golang mongodb

Currently I learn to create restful api with golang and mongodb. Actually I am beginner in both. I use mongodb-go-driver and I learn to use filter when we want to use find() function. But I have some that I don't understand. What is the different between filter := bson.M{"_id": "abcd"} and filter := bson.M{{"_id": "abcd"}}? Thank you



Solution 1:[1]

Refer to the source code, https://github.com/mongodb/mongo-go-driver/blob/master/bson/primitive/primitive.go

bson.D, internally is primitive.D, which is []primitive.E, which is a struct. bson.M, internally is primitive.M, which is map[string]interface{}. You put in key/value in bson.M but use document (struct) in bson.D.

It is better to explain it using 2 parameters, e.g. search for a = 1 and b = 2. You syntax will be: bson.M{"a": 1, "b": 2} or bson.D{{"a": 1}, {"b": 2}}

Solution 2:[2]

//Filter Part
if filter != nil {
    if len(filter.Status) > 0 {
        query = append(query, bson.M{"status": bson.M{"$in": filter.Status}})

    }
}
d.Shared.BsonToJSONPrint(query)
//Getting Total count
totalCount, err := col.Find(func() bson.M {
    if query != nil {
        if len(query) > 0 {
            return bson.M{"$and": query}
        }
    }
    return bson.M{}
}

Solution 3:[3]


    var user []models.User

    var findQuery []bson.M

    coll := db.C(constants.USERTABLE)

    if name != nil {
        if len(name) > 0 {
            query = append(query, bson.M{"name": bson.M{"$in": name}})

        }
    }

    if status != nil {
        if len(status) > 0 {
            query = append(query, bson.M{"status": bson.M{"$in": status}})

        }
    }

    findQuery = append(findQuery, bson.M{"$match": func() bson.M {
        if query != nil {
            if len(query) > 0 {
                return bson.M{"$and": query}
            }
        }
        return bson.M{}
    }()})

    shared.BsonToJSONPrint(query)

    err = coll.Pipe(findQuery).All(&user)
    if err != nil {
        return nil, err
    }
    return user, nil
}

Solution 4:[4]

The client decodes the result to a bson.D document by default, this is represented as an array, which is not the document shape we want.

To overwrite this behaviour you have to decode to a bson.M, which is a simple map and has the same shape of the document in database

res := collection.FindOne(ctx, p.Where)

if res.Err() == mongo.ErrNoDocuments {
    return nil, nil
}
if res.Err() != nil {
        return nil, res.Err()
}
var document bson.M = make(bson.M) // important
err = res.Decode(document)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 simagix
Solution 2 Kevin007
Solution 3 Kevin007
Solution 4 Morse