Sarus Crane
Sarus Crane

Reputation: 336

How to fetch matched record from two different collections in mongo

I want to fetch data from deposit and coin_info collection on which coin id will be same in both collections.

Here I am using lookup aggregation method.but am i am got empty array in result.

var mongoose=require('mongoose');

var data = mongoose.Schema({
    user_id: { type: String },
    coin_key: { type: String }  
});

var coin_info = new mongoose.Schema({
    _id: { type: String }   
    coin_code: { type: String }
});

var deposte_model = mongoose.model('deposit', data);

var get_coin_info = mongoose.model('coin_infos', coin_info);


var ccc=deposte_model.aggregate([
{ "$unwind": "$projects" },
{ "$unwind": "$projects.tags" },
{
  $lookup:
    {
      from: "get_coin_info",
      localField: "coin_key",
      foreignField: "_id",
      as: "inventory_docs"
    }
  },
{ "$unwind": "$inventory_docs" },
 {
    "$group": {
        "_id": null,
        "allTags": { "$addToSet": "$inventory_docs" },
        "count": { "$sum": 1 }
    }
}

]).exec(function(err, results){
console.log(results);
 });

Upvotes: 0

Views: 40

Answers (1)

Devang Naghera
Devang Naghera

Reputation: 706

Try changing type of coin_info to ObjectId and give reference to deposite schema

var coin_info = new mongoose.Schema({
_id:{type:String}   
coin_code:{
type:ObjectId,
ref:coin_infos/coin_info //Your collection name
}

});

Upvotes: 1

Related Questions