noDe1
noDe1

Reputation: 331

Joining two different collections form mongoDB in Node Js

I am new to mongoDB, and was wondering if the following is possible.

I have two different collection in the same mongo db table - called jobs and nodesand this is that they look like:

function testing() {
    nodes.find(function(err, data) {
        if (err) {
            console.log(err)
        } else {
            console.log('NODES RETURNED: ', data)

            jobs.find(function(err, post) {
                if (err) {
                    console.log(err)
                } else {
                    console.log('JOBS RETURNED: ', post)
                }
            });
        }
    });
}

Which returns the following:

JOBS RETURNED:  [ { _id: '5899999354d59',
    job_url: 'http://222.22.22.22:2222/jobs',
    progress: 0,
    queue: 0 },
  { _id: '5899b7d054da96',
    job_url: 'http://111.11.1.111:1111/jobs',
    progress: 0,
    queue: 0 } ]

CLUSTER NODESS RETURNED:  [ { _id: '58a9a4805c1f',
    node_url: 'http://222.22.22.22:2222/nodes',
    cpu: 40 },
  { _id: '58999a9a4805c23',
    node_url: 'http://111.11.1.111:1111/nodes',
    average_cpu: 15 } ]

So as you can see, the two different collections both have two documents each, and they can relate by the job_url and the node_url e.g. 222.22.22.22:2222 Is it possible for me to join the documents together based on this, so that the final result is something like this:

[ { _id: '58a9a4805c1f',
    node_url: 'http://222.22.22.22:2222/nodes',
    job_url: 'http://222.22.22.22:2222/jobs',
    progress: 0,
    queue: 0 },
    cpu: 40 },
  { _id: '58999a9a4805c23',
    node_url: 'http://111.11.1.111:1111/nodes',
    job_url: 'http://111.11.1.111:1111/jobs',
    progress: 0,
    queue: 0,
    average_cpu: 15 } 

Any help / tips would be really appreciated!

Upvotes: 0

Views: 87

Answers (1)

majdy abu adba
majdy abu adba

Reputation: 11

There is no join in mongo because mongo is a nosql database, read about it here https://en.wikipedia.org/wiki/NoSQL

In brief, nosql databases are used when fast retrieval and high availability of data is needed (join is slow so it's out of the game here), instead of that, when you get into situation like yours then you should think of remodeling your schema as explained well here https://docs.mongodb.com/manual/core/data-modeling-introduction

Ofcource you can do the join manually by yourself but then you miss the point of mongo

Upvotes: 1

Related Questions