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

如何在MongoDB中根据搜索ID查询并返回数组内的对应评论值

问题原因与解决方法

问题原因

  • 使用find()方法查询MongoDB数据时,返回的是FindCursor游标对象,而非直接的查询结果集,所以打印时只会输出游标对象的结构。
  • 现有查询逻辑只会返回包含匹配评论的整个餐厅文档,不会单独筛选出目标评论内容。

修改方案

调整查询逻辑,使用findOne()匹配单个餐厅文档,配合投影操作仅返回匹配的评论项,修改后的代码如下:

const ObjectId = require('mongodb').ObjectId;

async get(reviewId) {
    const restaurantsCollection = await restaurants();
    reviewId = ObjectId(reviewId);
    const restaurant = await restaurantsCollection.findOne(
      // 查询条件:匹配包含指定_id评论的餐厅
      { reviews: { $elemMatch: { _id: reviewId } } },
      // 投影规则:仅返回匹配到的第一条评论,不返回其他字段
      { projection: { "reviews.$": 1, _id: 0 } }
    );
    // 提取评论内容返回,无匹配时返回null
    return restaurant ? restaurant.reviews[0] : null;
}

修改后原index.js的调用逻辑无需调整,即可直接打印目标评论内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:57:05