Query in array with mongodb

Asked

Viewed 174 times

1

Good afternoon friends, I searched how to make a find inside an array in mongodb, looked at the documentation and so far in the forum and got no answer for my doubt.

my array it does not contain keys related to string: Ex: ["Name1", "Name2", "Name3"]

And in Mongo

0:"Name" 1:"Name2" 3:"Nome3"

{dados_basicos: {$elemMatch: {"0":"Nome1"}}}

nothing returns to me.

Look at my structure:

{
    "_id": "XXX",
    "atuacao": {},
    "cpf": "XXX",
    "dados_basicos": {
        "idLattes": "XXX",
        "NUMERO-IDENTIFICADOR": "XXX",
        "DATA-ATUALIZACAO": {
            "$date": {
                "$numberLong": "1598812002000"
            }
        },
        "NOME-COMPLETO": "Claudio Miceli de Farias",
        "NOME-EM-CITACOES-BIBLIOGRAFICAS": ["FARIAS, C. M.", "Farias, Claudio M.", "Miceli, C.", "MICELI, C.", "MICELI, C", "DE FARIAS, CLAUDIO M.", "MICELI, CLAUDIO", "Miceli, Claudio", "Claudio de Farias", "DE FARIAS, CLAUDIO", "FARIAS, CLAUDIO", "FARIAS, CLAUDIO M. DE", "FARIAS, CLAUDIO MICELI DE", "MICELI DE FARIAS, CLAUDIO", "MICELI FARIAS, C."],
        "NACIONALIDADE": "B",
        "PAIS-DE-NASCIMENTO": "Brasil",
        "UF-NASCIMENTO": "RJ",
        "CIDADE-NASCIMENTO": "Rio de Janeiro",
        }
}

my doubt is to be able to search inside that array {dados_basicos: {$elemMatch: {"0":"FARIAS, C. M."}}} and return the document to me

1 answer

1


If I have understood correctly, you need to find 1 or more documents containing the expression FARIAS, C. M. inside the array NOME-EM-CITACOES-BIBLIOGRAFICAS.

To have access to it with the operator $elemMatch, you need to specify the path of the nested object that contains this array as follows:

# O '.' faz a ligação entre os campos do objeto raiz com o aninhado
dados_basicos.NOME-EM-CITACOES-BIBLIOGRAFICAS

And the query would look like this - for a generic collection collection:

db.collection.find({
  "dados_basicos.NOME-EM-CITACOES-BIBLIOGRAFICAS": {
    $elemMatch: {
      $eq: "FARIAS, C. M."
    }
  }
})

Mongo Playground

Browser other questions tagged

You are not signed in. Login or sign up in order to post.