apc-unb / apc-api

MIT License
4 stars 0 forks source link

Mongo DB Filter #9

Closed VerasThiago closed 5 years ago

VerasThiago commented 5 years ago

Find a way to query like sql. Example of MongoDB website not working

db.inventory.find( { status: "A" }, { item: 1, status: 1, _id: 0 } ) Mongo SELECT item, status from inventory WHERE status = "A" SQL

vitordullens commented 5 years ago

In MongoCompass you have to click on "OPTIONS" on the side of the search bar and use the "PROJECT" section, in this section you put all the fields you want to be shown , like: FILTER : { status: "A" } PROJECT: { item: 1, status: 1, _id: 0 }

In the MongoShell itself you have to use the query: db.MyCollection.find( { status: "A" }, { item: 1, status: 1, _id: 0 } )

VerasThiago commented 5 years ago

The solution proposed by @vitordullens was correct, but the main point was how to implement this in Go, the answer was found here in Go section.

I was very close to solve this problem, because when you make a query in MongoDB, you can use a filter to restrict the documents. To show some specific data you need to specify the project (what you want to project). I was trying to find how to add this project into the query, here's the answer :

Add the project in the third parameter of the query function.

filter := bson.D{
    {"matricula", student.Matricula},
    {"password", student.Password},
}
projection := bson.D{
    {"password", 0},
}

if err := collection.FindOne(
    context.TODO(),
    filter,
    options.FindOne().SetProjection(projection),  // Solution here!
).Decode(&findStudent); err != nil {
    return findStudent, err
}