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

MongoDB Realm是否支持仅返回指定字段的查询(Projection)?

MongoDB Realm 实现类似PyMongo的Projection功能

当然可以,MongoDB Realm完全支持类似PyMongo的Projection(仅返回指定字段)功能,不同场景下的实现方式如下:

  • Realm Web SDK 查询时指定投影
    在Web端使用Realm SDK时,find()或findOne()方法的第二个参数可传入投影规则,逻辑和PyMongo一致:
const collection = db.collection('target-collection');
// 仅返回name、age字段,默认的_id会自动返回,需排除则添加_id: 0
const results = await collection.find({}, { name: 1, age: 1 });
// 排除_id的写法
const resultsWithoutId = await collection.find({}, { name: 1, age: 1, _id: 0 });
  • Realm Functions 中使用投影
    在Realm后台的自定义Functions里,直接使用MongoDB原生的投影语法即可:
exports = function() {
  const mongodb = context.services.get('your-cluster-service');
  const coll = mongodb.db('your-db').collection('your-collection');
  // 通过projection参数指定返回字段
  return coll.find({}, { projection: { title: 1, createdAt: 1 } }).toArray();
};
  • Realm移动SDK(iOS/Android/React Native)
    移动端SDK支持通过投影语法筛选返回字段,以React Native为例:
// 从YourModel集合中查询状态为active的文档,仅返回name和id字段
const projectedItems = realm.objects('YourModel')
  .filtered('status = "active"')
  .projectTo(['name', 'id']);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 07:18:10