[英]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
收集匹配_id
的coin_infos
与coin_id
的wallet_infos
和user_id
。
coin_infos collections coin_infos收藏
_id:objectID(5a4b07b2a0050c20a6be44b3),
coin_code:BTC,
wallet_name:bitcoin,
deposite_txn_fee:3,
min_withdrawn:5,
withdrawn_txn_fee:0.001,
wallet_infos collections wallet_infos集合
_id:objectID(5a58a4e222068e053d71220d),
user_id:5a4b0787a0050c20a6be44b2,
coin_id:5a4b07b2a0050c20a6be44b3,
balance:3.122858,
I have user ID -:5a4b0787a0050c20a6be44b2 我有用户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. 我的mongoDB版本是3.2.11。
you can use $lookup
and $match
aggregate pipeline, as you already on mongo version 3.2+ 您可以使用$lookup
和$match
聚合管道,因为您已经在mongo 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 $lookup
通过wallet_infos
上的coin_id
加入coin_infos
集合,如果找到匹配项,则钱包信息将作为嵌入式文档返回,从嵌入式文档user_id中,您可以进行$match
和过滤
db.coin_infos.aggregate(
[
{
$lookup : {
from : "wallet_infos",
localField : "_id",
foreignField: "coin_id",
as : "walletInfo"
}
},
{$match : {"walletInfo.userId" : "5a4b0787a0050c20a6be44b2"}}
]
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.