You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js Mongoose多集合查询:关联coin_infos与wallet_infos(MongoDB3.2.11)

如何用Mongoose实现指定条件的跨集合查询(MongoDB 3.2.11)

刚好做过类似的需求,针对MongoDB 3.2.11版本,用Mongoose的聚合框架就能完美实现你要的跨集合查询效果,下面是具体的解决方案:

1. 先确认模型定义(如果还没定义的话)

首先确保你已经为两个集合创建了对应的Mongoose模型,示例如下:

const mongoose = require('mongoose');

// coin_infos集合模型
const coinInfoSchema = new mongoose.Schema({
  coin_code: String,
  wallet_name: String,
  deposite_txn_fee: Number,
  min_withdrawn: Number,
  withdrawn_txn_fee: Number
});
const CoinInfo = mongoose.model('CoinInfo', coinInfoSchema, 'coin_infos');

// wallet_infos集合模型
const walletInfoSchema = new mongoose.Schema({
  user_id: mongoose.Schema.Types.ObjectId,
  coin_id: mongoose.Schema.Types.ObjectId,
  balance: Number
});
const WalletInfo = mongoose.model('WalletInfo', walletInfoSchema, 'wallet_infos');

2. 使用聚合管道实现关联查询

MongoDB 3.2开始支持$lookup(左连接)操作,结合其他聚合阶段就能实现你要的匹配逻辑,代码如下:

CoinInfo.aggregate([
  // 第一步:关联wallet_infos集合,匹配coin_infos._id = wallet_infos.coin_id
  {
    $lookup: {
      from: 'wallet_infos', // 要关联的集合名
      localField: '_id', // 当前集合(coin_infos)的匹配字段
      foreignField: 'coin_id', // 关联集合(wallet_infos)的匹配字段
      as: 'match_records' // 关联结果存储的数组字段名
    }
  },
  // 第二步:过滤出关联记录中user_id符合指定值的结果
  {
    $match: {
      'match_records.user_id': mongoose.Types.ObjectId('5a4b0787a0050c20a6be44b2')
    }
  },
  // 第三步:调整输出字段,添加wallet_balance并保留需要的字段
  {
    $project: {
      coin_code: 1,
      wallet_name: 1,
      deposite_txn_fee: 1,
      min_withdrawn: 1,
      withdrawn_txn_fee: 1,
      match_records: 1,
      // 从match_records数组中取出第一条的balance作为wallet_balance
      wallet_balance: { $arrayElemAt: ['$match_records.balance', 0] }
    }
  }
])
.exec()
.then(results => {
  console.log('查询结果:', results);
})
.catch(err => {
  console.error('查询出错:', err);
});

3. 代码说明

  • $lookup:实现两个集合的左连接,把wallet_infos中符合coin_id匹配的所有记录存入match_records数组
  • $match:过滤掉没有匹配到指定user_id的coin_infos记录,确保最终结果都是该用户关联的币种信息
  • $project:自定义输出字段,用$arrayElemAt从match_records数组中提取第一条记录的balance作为wallet_balance(如果一个币种对应用户有多条wallet记录,可以根据需求调整,比如用$sum计算总余额等)

执行这段代码后,输出结果就会和你期望的格式一致:包含coin_infos的基础字段、wallet_balance以及完整的关联记录数组match_records。

内容的提问来源于stack exchange,提问作者Sarus Crane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:08:04