Mongodb - Find sales containing two products

Asked

Viewed 42 times

0

I am a beginner in Mongodb and would like help with the following question. I have a Collection that has the following structure:

{[{id_venda:1, id_produto:20},
  {id_venda:1, id_produto:3332},
  {id_venda:1, id_produto:9},
  {id_venda:2, id_produto:20},
  {id_venda:2, id_produto:9},
  {id_venda:2, id_produto:7}
  {id_venda:3, id_produto:2980},
  {id_venda:4, id_produto:217}]}

How can I find sales containing products 9 and 20? In this case the returned result would be: 1 and 2

Code I tried to:

db.vendas.find({id_produto:{$elemMatch:{$eq:9,$eq:20}}})

But I know it’s not right, because the code above applies the filter on the same object and I would like to apply on top of the id_venda

Thank you in advance for helping me

  • Are you using mongodb with nde.js? Post the code you already tried! And how is the structure of product and sales collections?

  • The structure of the sale is the one I posted. In the relational bank would be something like a composite primary key, where the sale can the id_sale can be repeated as long as the Id_product is different.

  • I’m using Mongodb’s shell

  • I’m not sure I understand, this collection you posted seems to be a table resulting from an N:N relationship between products and sales, am I right? If yes put the structure of the product collection and the sales collection

  • No, in Mongodb we do not have tables but Collections, within the Sales & #Xa; Collection I have this object that is represented by this JSON structure. Relational Database concepts do not apply here.

  • Tables and collections are essentially the same thing with different names, although different, SQL concepts can and are applied to Nosql. For example, mongodb has the agregate (or something like that) equivalent to JOIN of SQL

Show 1 more comment

1 answer

0


The solution I found was the following:

db.collection.aggregate([

      //Primeiro filtro pelas vendas que contenha um dos produtos     
{$match:{$or:[{id_produto:9},{id_produto:20}]}},


      //Agrupo pelo id da venda contando a quantidade de vezes que aparece um 
     //registro (cada registro encontrado é referente a um dos produtos)     
{$group:{_id:"$id_venda",count:{$sum:1}}},

    //Então eu filtro onde foram encontrados os dois produtos
{$match:{"count":2}}
])

Browser other questions tagged

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