Search code examples
pythonmongodbpymongomongodb-aggregation

Distinct in MongoDB with space in key name


I have a collection with the following structure:

{'cnpj_fundo': '08.807.621/0001-93',
 'pl_posicao': 'R$ 8.654.202,31',
 'posicao': [{'empresa_ligada': 'Não',
   'quantidade_vendas': '',
   'detalhes': "{'Tipo de Ativo:': ['Fundo de Investimento e de Cotas'], 'Fundo:': ['BTGP ACCESS SELECTION FUNDO DE INVESTIMENTO EM COTAS DE FUNDOS DE INVESTIMENTO MULTIMERCADO'], 'Tipo de Aplicação:': ['Cotas de Fundos'], 'CNPJ:': ['05.892.577/0001-79']}",
   'categoria': '',
   'valor_vendas': '',
   'perc_carteira': '99,76',
   'quantidade_compras': '',
   'posicao_final': '8.633.395,56',
   'classificacao': '',
   'valor_custos ': '',
   'link': 'CDADetAplic.aspx?PkCDAAplic=7234077',
   'valor_compras': '4.657.681'},
  {'empresa_ligada': 'Não',
   'quantidade_vendas': '',
   'detalhes': "{'Tipo de Ativo:': ['Fundo de Investimento e de Cotas'], 'Fundo:': ['BTG PACTUAL YIELD DI FUNDO DE INVESTIMENTO REFERENCIADO CRÉDITO PRIVADO'], 'Tipo de Aplicação:': ['Cotas de Fundos'], 'CNPJ:': ['00.840.011/0001-80']}",
   'categoria': '',
   'valor_vendas': '',
   'perc_carteira': '0,235',
   'quantidade_compras': '',
   'posicao_final': '20.315,84',
   'classificacao': '',
   'valor_custos ': '',
   'link': 'CDADetAplic.aspx?PkCDAAplic=7234076',
   'valor_compras': '2.059'},
  {'empresa_ligada': '',
   'quantidade_vendas': '',
   'detalhes': "{'Tipo de Ativo:': ['Outros'], 'Descrição:': ['VALORES A RECEBER'], 'Tipo de Aplicação:': ['Valores a receber']}",
   'categoria': ' VALORES A RECEBER',
   'valor_vendas': '',
   'perc_carteira': '0,006',
   'quantidade_compras': '',
   'posicao_final': '490,91',
   'classificacao': 'Paranegociação',
   'valor_custos ': '',
   'link': 'CDADetAplic.aspx?PkCDAAplic=7234078',
   'valor_compras': ''}],
 'nome_fundo': 'FUNDO DE INVESTIMENTO MULTIMERCADO CRÃ\x89DITO PRIVADO BOA ESPERANÃ\x87A - INVESTIMENTO NO EXTERIOR',
 'data_carteira': '10/2007',
 '_id': ObjectId('573d22f7a5c5da185c67fbd7')}

How can I get the "distinct" values for "Tipo de Ativo:"?

db.distinct("posicao.detalhes.Tipo de Ativo:")

does not work.

Any thoughts?


Solution

  • First, you have a problem with your records. The values of 'detalhes' are not BSON, they are strings (JSON) but this makes querying a lot harder.

    So you need to go a head and update your records. In Python you can to that with:

    import json
    updated_value = json.loads(value_of_detalhes)
    db.update( ... {"$set": {"detalhes": updated_value}})
    

    After you modified the JSON formated string you can go and use the aggregation framework find the distinct values. Here is an example:

    > db.foo.find()
    { "_id" : ObjectId("573...94"), "p" : [ { "d" : { "tda" : [ "y" ] } } ] }
    { "_id" : ObjectId("573...95"), "p" : [ { "d" : { "tda" : [ "x" ] } } ] } 
    

    Note how my dummy records have similar structure to you records. They differ in that the value of d is BSON. Never the less d is the parallel to your detalhes. Once you modified the JSON to BSON you can do:

    > db.foo.aggregate([{$group: {_id: "$p.d.tda"}}])
    { "_id" : [ [ "x" ] ] }
    { "_id" : [ [ "y" ] ] }
    

    And so you find that the embedded field tda has 2 distinct values.

    My snippets are in JS (using mongo shell) but the principle with Python remains the same.