Search code examples
databasemongodbnosqlaggregatenosql-aggregation

Mongodb Aggregate lookup all products from one specific client


I have a Database from a .data and these collections: clientes, mercancias and vagones. I want to find all the data of mercancias from the same client. So in this case, "Electronica Chispas" has 2 "mercancia" entities in the database:

[{"cliente": {"nombre": "Cafes el amanencer"},
 "mercancia": {"envio": "Normal", "tipo": "Gaseoso", "fecha": "24/12/2003", "peso": 21, "volumen": 43, "origen": "Cadiz", "destino": "Castellon"},
 "vagon": {"id": 1330, "volumen": 202, "peso": 433 }},{"cliente": {"nombre": "Electronica Chispas"}, "mercancia": {"envio": "Normal", "tipo": "Liquido", "fecha": "08/02/2005", "peso": 17, "volumen": 24, "origen": "San Sebastian", "destino": "Orense"}, "vagon": {"id": 1290, "volumen": 111, "peso": 464 }},{"cliente": {"nombre": "Electronica Chispas"}, "mercancia": {"envio": "Urgente intradia", "tipo": "Contaminante", "fecha": "15/09/2002", "peso": 11, "volumen": 83, "origen": "Valladolid", "destino": "Ciudad Real"}, "vagon": {"id": 1315, "volumen": 115, "peso": 481 }}]

I am trying this query:

db.mercancias.aggregate([{$lookup:{'from': 'clientes', 'localField':'destino', 'foreignField': 'nombre', 'as': 'clientes'}}])

But it is not working how I want to. Of course, I am missing to write the "Electronica Chispas" name somewhere in that query, but I am not sure where to write it.


Solution

  • In MongoDB, having duplicate data is not important nor an issue!

    Making how to join was impossible. I decided to add in mercancias an id of vagonand nombreof clientes, so the relation could be named. That way, there was no need to do LookUpin mongo, and a "simple" aggregate query could be done!