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

Prisma MongoDB:能否限制Scalar List查询返回单条数据?

Prisma标量列表单条数据查询方案

针对你定义的Prisma模型,直接通过Prisma Client的常规查询语法无法仅返回results标量列表中的单条数据,因为Prisma目前不支持对标量列表进行切片、限制返回条数的原生操作。

不过可以通过以下两种方式实现需求:

1. 应用层处理

先查询完整的Test记录,再在应用代码中提取results数组的单条数据:

const testRecord = await prisma.test.findUnique({
  where: { id: "你的文档ID" },
  select: { results: true }
});

// 取数组第一条数据
const singleResult = testRecord?.results[0];
// 或者返回长度为1的数组(如需保持数组格式)
const singleResultArray = testRecord?.results.slice(0, 1);

2. 使用MongoDB原生查询(仅适用于MongoDB数据库)

由于你的模型使用了@db.ObjectId,底层数据库为MongoDB,可以通过Prisma的原生查询功能,借助MongoDB的$slice操作符直接返回指定条数的列表数据:

const result = await prisma.$queryRaw`
  SELECT results FROM Test 
  WHERE _id = ${ObjectId("你的文档ID")} 
  LIMIT 1
  PROJECTION { results: { $slice: 1 } }
`;

也可以用聚合管道实现:

const result = await prisma.$queryRaw`
  db.Test.aggregate([
    { $match: { _id: ${ObjectId("你的文档ID")} } },
    { $project: { results: { $slice: [ "$results", 1 ] } } }
  ])
`;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 14:55:26