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

MongoDB Atlas应用服务函数查询文档遇$in数组错误

解决MongoDB Atlas应用服务函数查询报错“$in needs an array”

问题场景

我在MongoDB Atlas应用服务函数中尝试查询文档,集合已有记录,用MongoDB Compass执行以下命令能成功查到结果:

use SomeDatabase
db.MyCollection.findOne({})

但创建应用服务函数执行空查询时,无论尝试何种查询方式,都会报错:Error occurred while executing findOne: $in needs an array。函数代码如下:

exports = async function(assetId, rendition) {
  var serviceName = "mongodb-atlas";
  var dbName = "SomeDatabase";
  var collName = "MyCollection";
  var collection = context.services.get(serviceName).db(dbName).collection(collName);

  var findResult;
  try {
    findResult = await collection.findOne({});
  } catch(err) {
    console.log("Error occurred while executing findOne:", err.message);
    return { error: err.message };
  }

  return {
    result: findResult,
  };
};

排查与解决步骤

1. 检查集合的数据访问规则(最可能原因)

Atlas应用服务的数据访问规则会在函数执行查询前自动生效,哪怕你的函数查询语句是空的,规则里的错误也会触发该报错:

  • 登录MongoDB Atlas控制台,进入目标App Services项目
  • 左侧菜单进入Data Access -> Rules,定位到MyCollection对应的规则
  • 检查规则条件是否使用了$in操作符,比如类似:
    { "groupIds": { "$in": %%user.custom_data.groupIds%% } }
    
  • 确认占位符对应的变量(如%%user.custom_data.groupIds%%)是否为数组类型,若该变量不存在或为非数组值,就会触发$in needs an array错误
  • 临时测试:将该集合规则临时设置为允许所有读写(仅限测试,生产环境需恢复严格规则),重新运行函数,若报错消失,即可确认是规则问题,调整规则逻辑即可。

2. 检查函数参数传递

函数定义包含assetId, rendition两个参数,但测试时调用exports();未传参,虽然函数内未使用这两个参数,但Atlas函数的参数传递异常可能引发隐性错误:

  • 修改函数定义,移除未使用的参数:
    exports = async function() {
      // 原函数逻辑不变
    };
    
  • 或在测试控制台调用时传递符合要求的参数(如exports("test-id", "test-rendition")),再测试查询是否正常。

3. 检查集合索引(概率较低)

虽然Compass能正常查询,但如果集合存在错误配置的索引(比如索引定义中错误使用$in),也可能引发异常:

  • 在MongoDB Compass中查看MyCollection的索引列表,检查是否有包含$in的异常索引,如有则删除后重新测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 10:55:30