D
D
Denis Sokolov2022-04-09 14:48:20
MongoDB
Denis Sokolov, 2022-04-09 14:48:20

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"`
}

This function works with a DB. If answers = true then everything works fine. But if answers = false then immediately an error
(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

2 answer(s)
U
uvelichitel, 2022-04-09
@Denis147258369

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,
    },
}

And vice versa, this is how it should work:
bson.M{
    "tasks": bson.M{
      "answer":  0,
    },
}

Or what we want to include or exclude.

D
Dmitry Bezmenov, 2022-04-09
@rand_nickname

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.

you cannot mix the exception and the selection of fields, that is, you need to take the answers upstairs and include it only if necessary

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question