简体   繁体   中英

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 nodes and 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 eg 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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM