Sarus Crane
Sarus Crane

Reputation: 336

node js mongoose how to fetch record from two collection

In that below collections I want to try fetch all record from coin_infos collection matching _id of coin_infos with coin_id of wallet_infos and user_id.

coin_infos collections

_id:objectID(5a4b07b2a0050c20a6be44b3),
coin_code:BTC,  
wallet_name:bitcoin,
deposite_txn_fee:3,
min_withdrawn:5,
withdrawn_txn_fee:0.001,

wallet_infos collections

 _id:objectID(5a58a4e222068e053d71220d),
 user_id:5a4b0787a0050c20a6be44b2,
 coin_id:5a4b07b2a0050c20a6be44b3,
 balance:3.122858,

I have user ID -:5a4b0787a0050c20a6be44b2

output look like this:..

{

_id:objectID(5a4b07b2a0050c20a6be44b3),
coin_code:BTC,
wallet_balance:3.122858,
wallet_name:bitcoin,
deposite_txn_fee:3,
min_withdrawn:5,
withdrawn_txn_fee:0.001,

"match_records" : [

_id:objectID(5a58a4e222068e053d71220d),
user_id:5a4b0787a0050c20a6be44b2,
coin_id:5a4b07b2a0050c20a6be44b3,
balance:3.122858,
 ] 
} 

My mongoDB version is 3.2.11.

Upvotes: 1

Views: 77

Answers (1)

Saravana
Saravana

Reputation: 12817

you can use $lookup and $match aggregate pipeline, as you already on mongo version 3.2+

$lookup joins coin_infos collection with wallet_infos on coin_id, if match found, the wallet info will be returned as a embedded document, from the embedded documents user_id you can do $match and filter

db.coin_infos.aggregate(
    [
        {
            $lookup : {
                from : "wallet_infos",
                localField : "_id",
                foreignField: "coin_id",
                as : "walletInfo"
            }
        },
        {$match : {"walletInfo.userId" : "5a4b0787a0050c20a6be44b2"}}
    ]
)

Upvotes: 1

Related Questions