Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a mongodb Document that field value match with some item of input array

I have a string list with the dates of the days of a given week.

String daysweek[] = ["10/05/2020", "11/05/2020", "12/05/2020", "13/05/2020", "14/05/2020", "15/05/2020", "16/05/2020" ]

My goal is to be able to find several documents that belong to a certain week. The comparison field is "firstday".

Follows the image of the document structure in the database:

enter image description here

 Document insert = new Document().append("$elemMatch", daysweek[]);
       Document filterstar = new Document().append("id_motorista", idmotorista).append("pagamento", false).append("firstday", insert);

        coll.find(filterstar).projection(new Document().append("_id", 1).append("origem",1).append("destino", 1).append("formadepagamento", 1).append("valordaviagem",1)
                .append("notamotorista",1).append("pagamento",1).append("iniciodaviagem", 1).append("fimdaviagem",1).append("viagemcancelada", 1).append("horadaaceitacao",1)
                .append("horacancelamentomotorista", 1).append("horacancelamentousuario", 1).append("taxadecancelamento", 1).append("valordaviagemmotorista", 1).append("valordaviagemusuario", 1).append("id_acompanhamento",1)
                .append("taxaaplicativo", 1).append("taxacartao", 1).append("taxamotorista", 1)).sort(new Document().append("firstday", 1)).limit(100)
                .into(docs).addOnSuccessListener(new OnSuccessListener<List<Document>>() {
            @Override
            public void onSuccess(List<Document> documents) {}

But the search finds no documents. The number of queries expected would be 35.

I would like to know if there is any way to find documents through a given document field, match any of the items within an arraylist.

like image 777
João Gabriel Araujo Avatar asked Dec 07 '25 08:12

João Gabriel Araujo


1 Answers

$elemMatch is used when you're querying against an array field, but in your scenario you're querying against a string field and input is an array, then you can just use $in operator.

Mongo Shell Syntax :

db.collection.find({firstday : {$in : ["10/05/2020", "11/05/2020", "12/05/2020", "13/05/2020", "14/05/2020", "15/05/2020", "16/05/2020"]}})

Test : mongoplayground

like image 170
whoami - fakeFaceTrueSoul Avatar answered Dec 09 '25 21:12

whoami - fakeFaceTrueSoul