Search code examples
mongodbdata-structuresmongodb-querydatamodel

Mongodb equivalent of RIGHT JOIN - Data may be in collection A or B, should I combine collections or lookup twice?


I'm new to MongoDB, coming from a SQL background

I have two collections of orders:

  • A: Includes payments made using a website
  • B: Includes payments made using an app

I want to summarise data for customers and the issue i'm facing is that I can't simply do lookup since some customers will only use B ever, so they'll be excluded

What would be the best way to do this?

I'm hesitant to create a brand new collection, embedding A and B, at the customer level since that'll be duplicating data and space is an important consideration


Here is a sample of A and B:

A (website):

{
"_id": 1,
customer_id: 2,
order_id: 1188,
date: "2018/06/01",
item_id: "1",
item_name: "Item 1",
amount_paid: 30
}

B (app):

{
"_id": 12,
customer_id: 2,
order_id: 1247,
date: "2018/04/01",
item_id: "2",
item_name: "Item 2",
amount_paid: 8
},
{
"_id": 13,
customer_id: 4,
order_id: 2532,
date: "2018/08/02",
item_id: "2",
item_name: "Item 2",
amount_paid: 8
}

Important note: The vast majority of orders are made using website (A)

What would be the best practice here?


Basic questions i'm trying to answer:

"How many orders are there for customer x?" where x could have used (A and B) or (A or B)


Expected output:

{
"_id": 1,
customer_id: 2,
order_id: 1188,
date: "2018/06/01",
item_id: "1",
item_name: "Item 1",
amount_paid: 30
},
{
"_id": 12,
customer_id: 2,
order_id: 1247,
date: "2018/04/01",
item_id: "2",
item_name: "Item 2",
amount_paid: 8
},
{
"_id": 13,
customer_id: 4,
order_id: 2532,
date: "2018/08/02",
item_id: "2",
item_name: "Item 2",
amount_paid: 8
}

In the expected output you can see that all customer_id 2 had both orders from A and B, and customer_id 4 (that didn't appear in A) was also included


MongoDB version - 4.0.1


Thanks in advance


Solution

  • I found out I can simply do this:

    db.B.find().forEach (
        function(x) {
            db.A.insert(x)
            } )
    

    And what this does is "for every document in B, insert as a new document into collection A"