Answer the question
In order to leave comments, you need to log in
How to query only a few fields?
This is my structure.
type Test struct {
Id primitive.ObjectID `json:"id" bson:"_id,omitempty" db:"_id"`
Tasks []Task `json:"tasks" bson:"tasks" db:"tasks"`
}
type Task struct {
Description string `json:"description" bson:"description" db:"description"`
Answer string `json:"answer" bson:"answer" db:"answer"`
Balls int `json:"balls" bson:"balls" db:"balls"`
}
(Location31254) Cannot do exclusion on field answer in inclusion projection
func (r *TestsRepo) GetTestByIdRepo(id string, answers bool) (*vpr.Test, *vpr.Error) {
var test vpr.Test
objectId, errID := primitive.ObjectIDFromHex(id)
if errID != nil {
return nil, SetError(http.StatusNotFound, "Is not a valid ObjectID")
}
options := options.FindOne().SetProjection(bson.M{
"tasks": bson.M{
"answer": answers,
"balls": true,
"description": true,
},
})
filter := bson.M{"_id": objectId}
err := r.db.FindOne(nil, filter, options).Decode(&test)
if err != nil {
return nil, SetError(http.StatusInternalServerError, err.Error())
}
return &test, nil
}
Answer the question
In order to leave comments, you need to log in
You just don't need to include answer in the Projection at all. Should be enough:
bson.M{
"tasks": bson.M{
"balls": 1,
"description": 1,
},
}
bson.M{
"tasks": bson.M{
"answer": 0,
},
}
https://www.mongodb.com/docs/manual/tutorial/proje...
With the exception of the _id field, you cannot combine inclusion and exclusion statements in projection documents.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question