MongoDB Shell code for left join recursive in one collection

40 Views Asked by At

What are the details of your problem?

I have a two colletions called nodes and organisations.

Problem 1: left join for same collection

In nodes there is an attribute called kind, there are three kinds A,B,C, and each kinds have slightly different schema, in A, there is _b attribute which link to B's object ID: _id, in B, _c object ID link to other collection organisations.

Problem 2: left join recursively

In organisations's C, there is a _parentOrg ObjectID which link to another document in organisations and I don't know how many parent it have, so need do it recursively.

What did you try and what were you expecting?

I tried with $lookup but that is only for two collections, not for one collection.

Minimal reproducible example:

collection:nodes:

A:

{
    "_id": {
      "$oid": "53a7892a0c4ec9a238378c30"
    },
    "_b": {
      "$oid": "54fe2bf27dab2fd24e61e26b"
    },
    "serial": "aaaaaaaaaaaaa",
    "kind": "A type",
    "name": "A123",
    "active": true,
    "createdDate": {
      "$date": "2014-06-23T01:55:54Z"
    }
  }

B:

{
    "_id": {
      "$oid": "54fe2bf27dab2fd24e61e26b"
    },
    "_c": "5f0b9d810e170b6f2337073d",
    "dateFormat": "DD/MM/YYYY",
    "kind": "Factory",
    "name": "L University",
    "active": true,
    "isTemplateSite": false,
    "createdDate": {
      "$date": "2015-03-09T23:25:38Z"
    },
     "address": {
      "suburb": "CFD",
      "city": "XXX city",
      "country": {
        "$oid": "5398fa6e2d764afe32a29aac"
      },
      "street": "21 New ave"
    },
  }

collection:organisations:

C:

{
    "_id": {
      "$oid": "5f0b9d810e170b6f2337073d"
    },
    "name": "SPIP",
    "_parentOrg": {
      "$oid": "5702f5161c852788280926f3"
    },
    "_country": {
      "$oid": "5398fa6e2d764afe32a29aac"
    },
    "isNotBillable": false,
  }

C1:

{
    "_id": {
      "$oid": "5702f5161c852788280926f3"
    },
    "name": "KJSLKDJ LTD",
    "_parentOrg": null,(or no such attribute)
    "_country": {
      "$oid": "5398fa6e2d764afe32a29aac"
    },
    "isNotBillable": true,
  }

NOTE: some time you there are only two layers no _parentOrg or _parentOrg=null then stop

Expected

I want to do some join like enrich A with B, then enrich the result from previous with C(and C's parents if possible) by left join. Also there are some duplicated attributed in A,B,C, like name, after the whole join, I want something like {A.name, B.name, C.name, C1.name}, I'd like keep everything without project, but the resutl need easy to differentiate which attribute from A or B or C.

0

There are 0 best solutions below