简体   繁体   中英

How to join _id with nested _id MongoDB

I'm working on project that required to joined nested _id with and _id for exemple I have

Collection TPE looks like this

{
sn:[{sn:0001,TPE_id:01},{sn:0001,TPE_id:02},{sn:0001,TPE_id:03},{sn:0001,TPE_id:04}],
sellerName:'XXX',
networkType:'GPRS'
}

And I have collection transaction that looks like this

{
TPE_id:01,
transactionAmount:'XXX',
transactionType:'DECLINED'
}
{
TPE_id:01,
transactionAmount:'XXX',
transactionType:'APPROVED'
}
{
TPE_id:02,
transactionAmount:'XXX',
transactionType:'APPROVED'
}
{
TPE_id:04,
transactionAmount:'XXX',
transactionType:'CANCELED'
}

How can I join to get the transaction of related TPE_id for exemple

newArray 1 : [ {
    TPE_id:01,
    transactionAmount:'XXX',
    transactionType:'DECLINED'
    }
    {
    TPE_id:01,
    transactionAmount:'XXX',
    transactionType:'APPROVED'
    }]
newArray2 [{
    TPE_id:04,
    transactionAmount:'XXX',
    transactionType:'CANCELED'
    }]
newArray3 [  {
    TPE_id:02,
    transactionAmount:'XXX',
    transactionType:'APPROVED'
    }]

Questions

Can i do a loop through sn array to martch all the TPE_id with their related transaction ?
In case I have multiple Sn each Sn has array of TPE_id I want to get sn of specific id ?
Sorry for my bad english

Here are the hints

  1. Unwind sn field of TPE collection , it will restructure your array documents
  2. Then do a $lookup on Transactions collection
  3. Use project to get the desired o/p format

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