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

如何在MongoDB中同时查询多个集合,筛选星级大于3的文档

MongoDB多集合联合查询实现方案

以下针对MongoDB数据库场景,给出两种可行实现方式:

方案1:聚合管道联合查询(推荐,MongoDB 4.4+版本支持)

通过$unionWith操作符直接在数据库侧完成多集合联合+条件筛选,无需应用侧二次处理:

// 切换到目标数据库
use dbcosos;

db.books.aggregate([
  // 筛选当前books集合符合要求的文档
  {
    $match: {
      stars: { $exists: true, $ne: null, $gt: 3 }
    }
  },
  // 联合foods集合筛选
  {
    $unionWith: {
      coll: "foods",
      pipeline: [
        { $match: { stars: { $exists: true, $ne: null, $gt: 3 } } }
      ]
    }
  },
  // 联合movies集合筛选
  {
    $unionWith: {
      coll: "movies",
      pipeline: [
        { $match: { stars: { $exists: true, $ne: null, $gt: 3 } } }
      ]
    }
  }
])

说明:匹配条件中加入$exists: true和$ne: null是为了过滤掉无stars字段、stars值为空的无效文档,适配你给出的集合结构特性。

方案2:低版本MongoDB兼容方案

如果你的MongoDB版本低于4.4(不支持$unionWith特性),可以分别查询三个集合后合并结果:

use dbcosos;

// 复用筛选条件
const filterRule = { stars: { $exists: true, $ne: null, $gt: 3 } };
// 分别查询三个集合
const booksRes = db.books.find(filterRule).toArray();
const foodsRes = db.foods.find(filterRule).toArray();
const moviesRes = db.movies.find(filterRule).toArray();
// 合并所有符合条件的结果
const finalResult = [...booksRes, ...foodsRes, ...moviesRes];

示例数据匹配结果

针对你给出的测试数据,最终符合条件的条目共2条:

  • books集合中stars值为4的文档
  • movies集合中stars值为7的文档

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 02:39:03