如何使用 Node.js 仅获取 MongoDB 中的部分文档?

问题描述

"Geography": {
  "Tourism": {
    "B001": {
      "code": "B001","max": " 140","min": " 97","minWithQuota": " 91"
    }
  }
},"MathAndPhysic": {
  "IT": {
    "B183": {
      "code": "B183","max": "140","min": " 50","minWithQuota": "none","quotes": []
    }
  }
}

我有一些收藏,我只想得到“B001”对象。我试过了

db.subjects.findOne (
{"Geography.Tourism.B001": {$exists: true}},{_id: 1," Geography.Tourism.B001": 1})

但结果是整个文档。我如何得到这个结果?

"B001": {
      "code": "B001","minWithQuota": " 91"
    }

附言有趣的是,如果您尝试在 MongoShell 中使用相同的命令,您将获得所需的结果

解决方法

尝试使用参考 $ 投影字段,

db.subjects.findOne(
  { "Geography.Tourism.B001": { $exists: true } },{ "B001": "$Geography.Tourism.B001" }
);

Playground