Mongodb Agregation + Lookup

2

Good evening, I need to relate two collections in mongodb, they are:

db.markets db.products

db.mercados.find()
{
  "_id": ObjectId("5bb90160995e46f1fdbf1fe8"),
  "nome_mercado": "teste",
  "localidade": "são paulo",
  "pagamentos": [
    "credito",
    "débito",
    "dinheiro",
    "vr",
    "va"
  ],
  "produtos": [
    {
      "ean": "9876",
      "preco": "2,00"
    },
    {
      "ean": "123",
      "preco": "1,99"
    }
  ],
  "data_de_atualizacao": "Sat Oct 06 2018 15:39:24 GMT-0300"
}


db.produtos.find()
{
  "_id": ObjectId("5bb78c13ec8dee50a692d18f"),
  "ean": "123",
  "nome_produto": "Corona",
  "Categoria": "Cerveja"
}
{
  "_id": ObjectId("5bb78c5fec8dee50a692d190"),
  "ean": "9876",
  "nome_produto": "passa tempo",
  "Categoria": "Bolacha"
}
{
  "_id": ObjectId("5bb78f57844b17c8cadd039c"),
  "ean": "9876",
  "nome_produto": "traquinas",
  "Categoria": "Bolacha"
}
{
  "_id": ObjectId("5bb78f9b844b17c8cadd039d"),
  "ean": "98765",
  "nome_produto": "cramecrack",
  "Categoria": "Bolacha"
}

I need something like this:

{
  "_id": ObjectId("5bb90160995e46f1fdbf1fe8"),
  "nome_mercado": "teste",
  "localidade": "são paulo",
  "pagamentos": [
    "credito",
    "débito",
    "dinheiro",
    "vr",
    "va"
  ],
  "produtos": [
    {
      "ean": "9876",
      "preco": "2,00"
      "nome_produto": "traquinas",
      "Categoria": "Bolacha"
    },
    {
      "ean": "123",
      "preco": "1,99"
      "nome_produto": "Corona",
      "Categoria": "Cerveja"

    }
  ],
  "data_de_atualizacao": "Sat Oct 06 2018 15:39:24 GMT-0300"
}

I need to relate the two collections, can anyone help me?

    
asked by anonymous 07.10.2018 / 05:27

1 answer

1

Friend,

Unlike the SQL paradigm, where you list tables and cross data in the query, in MongoDB (NoSQL) you will not list lists.

You have two possibilities here:

  • Find the desired market in the 'markets' collection, and take product IDs (EANs) to then fetch each product to get the additional information you need in the application, or

  • Create redundancy of product data in the 'market.products' list of your 'markets' collection, so that you already have all the required data in the market query.

    The second option will certainly scale better, is best suited for NoSQL databases.

    In non-relational databases such as MongoDB, worry about structuring the data at the time of writing to the collections, creating the necessary redundancies, so that the query will be ready for direct use.

        
  • 11.10.2018 / 23:19