Mongo query to filter with an array specific index based on parameters

I have a few documents in a mongoDB that have the following structure

enter image description here

In a API web application that I am developing with spring boot I have to code the following query. I can receive a voltageLevelCode to filter register that will contains this voltage level code in the array (That it is easy) but the problem is that i can also receive a voltageLevelCode and a Type, so in this case I have to filter documents that will contains this voltage level code in the array and also WITHIN this voltage level code filter the ones that contains this type (But remember, the type within the voltage level) I have been trying to write the query but I dont know how to dynamically set the index to filter the types within this voltage level. Something like:

{"voltageLevel.<TheIndexByTheDefinenVoltageLevelCode>.types" : "X" }

Example:

public List<MyClassRepresenting> findByFilter(String type,String voltageLevelCode);
{$and: [{'voltageLevel.voltageLevelCode' : ?1 },{'voltageLevel.<HowTogetIndexForSelectingVoltageLevelCode>.types' : ?2}]}

In this case depending on the tensionLevel received the type parameter must filter according to types within this tensionLevel

Same happens to me with another query. In SQL the equivalent is the SELECT within another SELECT to select the sub registers but no idea about how to do it in mongo.

Upvotes: 0

Views: 1136

Answers (1)

GeertPt
GeertPt

Reputation: 17874

When asking a question on stackoverflow, it's always interesting to include what you already tried.

I think what you need is a simple $elemMatch:

db.mycoll.find(
  { voltageLevel: { $elemMatch: { voltageLevelCode: "MT", types: "E" } } }
)

Upvotes: 1

Related Questions