-3

i am new in mongodb database, i want to fetch data from two different collections ( like in mysql use of joins) then how can we do this in mongodb ? Here my collections data

First collection 

{
    "id": "5b67dbf20b9f9d2830ccaf40",
    "title": "Some Text",
    "author": "John Doe"
}


Second collection 

{
    "id": "5b67dbyd48btr9jexya8ehd8",
    "pid": "5b67dbf20b9f9d2830ccaf40",
    "salary": "50000"
}
  • Please look into $lookUp. Ref Link : https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/ – IftekharDani Aug 06 '18 at 06:17
  • 1
    Possible duplicate of [How do I perform the SQL Join equivalent in MongoDB?](https://stackoverflow.com/questions/2350495/how-do-i-perform-the-sql-join-equivalent-in-mongodb) – Ashh Aug 06 '18 at 06:28

1 Answers1

0

Update your NewSchema as:

var NewSchema = mongoose.Schema({
    pid: {
            type: Mongoose.Schema.ObjectId,
            ref: `Firstcollection`
        }
    });

You can solve it using populate from mongoose.

SecondCollection.find({})
.populate('pid')
.exec(function(err, data) {
    console.log(data)
})

Hope it solves your query!!

Harshal Yeole
  • 4,812
  • 1
  • 21
  • 43
  • not working , showing record of first collection only , i want to to get data where both id ( id in first collection and pid in second collection ) matchs – Neha Gupta Aug 06 '18 at 06:33
  • What exactly you want to achieve? Can you share the schema with data in question and the expected result? – Harshal Yeole Aug 06 '18 at 06:55
  • @NehaGupta If the above query is not working then I think you don't have first and esecond collection linked using **ref**. – Harshal Yeole Aug 06 '18 at 06:56
  • i want to fetch records from both collections. Thats it! – Neha Gupta Aug 06 '18 at 08:00
  • Can you post your model schema? – Harshal Yeole Aug 06 '18 at 08:09
  • Here is my code of model , ( my collections names are firstcollection and second collection) var mongoose = require('mongoose'); var UserSchema = mongoose.Schema({ name : { type : String, required : true }, email : { type : String, required : true, unique: true }, phone : String }); const User = module.exports = mongoose.model('Firstcollection', UserSchema); var NewSchema = mongoose.Schema({}); const Newuser = module.exports = mongoose.model('Secondcollection', NewSchema); – Neha Gupta Aug 06 '18 at 09:05
  • Update your NewSchema as I have added it in question and try the given query now. – Harshal Yeole Aug 06 '18 at 09:54