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
4 Answers
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}}
//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{}
}
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
}
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)
filter := bson.M{{"_id": "abcd"}}
doesn't compile, so I don't know what you're asking. Maybe you meanfilter := []bson.M{{"_id": "abcd"}}
? That's a slice, a slice of "filters", most often used when specifying stages of a MongoDB aggregation.filter := bson.D{{"_id": "abcd"}}
. Usebson.D{{}}
when order matters, for example, multiple fields in the query filter. Either onebson.D
orbson.M
as filters, mongo engine is intelligent enough to give you the same result.bson.D{{}}
mean? Doesbson.M
havebson.M{{}}
form?filter := bson.M{"_id": id}
and thisfilter := bson.D{{"name", "Ash"}}
so whybson.D
use double braces{{}}
? What does it mean?