node.js - MongoDB 投影参数在 findOne() 中不起作用
问题描述
我正在尝试在 findOne() 上使用投影参数从文档(统计信息)中提取单个字段,但它似乎只是返回了整个文档。我在 Node.js 中使用版本“mongodb”:“^3.4.1”
这是文档结构
{ _id: 5e563015fa9a1a0134cac3cb,
username: 'user1',
password: '1234',
email: 'user@email.com',
stats:
{ totalViewed: 122,
totalUnique: 4,
tknow: 80,
tdknow: 42,
setCnt: 78 },
progress:
[ { cardId: 1001, knowCnt: 3, dknowCnt: 4 },
{ cardId: 1016, knowCnt: 0, dknowCnt: 0 } ] }
这是代码:
var findOneDoc = function() {
db.collection("testusers").findOne(
{ username: "user1" },
{ stats: 1 }, //field to return
function(err, result) {
if (err) {
console.log("Error: ", err);
}
console.log("Success: ", result);
}
);
};
findOneDoc();
我也试过:{$project: {stats: 1}}
,无济于事
谢谢
解决方案
根据文档,该.findOne()
方法将选项作为第二个参数,建议用于projection
定义字段:
db.collection("testusers").findOne(
{ username: "user1" },
{ projection: { stats: 1 } },
function(err, result) { ... }
);
推荐阅读
- python - 检查列表是否包含用户输入的字符串
- python-3.x - Matplotlib:textcolor 不显示任何颜色
- vue.js - 如何在 Vue3 中将 cdn 作为 es6 模块导入?
- python - ZipFile.extractall 从 zip 中删除文件,但不会将它们保存在任何地方
- java - 未为特定文件夹和所有子文件夹设置 Java 版本
- apache-spark - Spark JDBC:spark.read 中的语法不正确
- javascript - 时间输入通过时刻验证
- azure - QueryAzureDevOpsExtensionVersion - 找不到区域的 api 位置:画廊 id
- google-sheets - 谷歌表格 - 数组索引匹配多个条件
- postgresql - 如何从不再存在的数据中清除 docker 卷?