本文介绍了MongoDB 投影参数在 findOne() 中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 findOne() 上的投影参数从文档 (stats) 中提取单个字段,但它似乎只是返回整个文档.我在 Node.js 中使用版本mongodb":^3.4.1"
I'm trying to use a projection parameter on findOne() to extract a single field from a document (stats) but it just seems to return the whole document. I'm using version "mongodb": "^3.4.1" in Node.js
这是文档结构
{ _id: 5e563015fa9a1a0134cac3cb, username: 'user1', password: '1234', email: 'user@email', 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 定义字段:
Based on the documentation the .findOne() method takes options as a second parameter and it is recommended to use projection to define fields:
db.collection("testusers").findOne( { username: "user1" }, { projection: { stats: 1 } }, function(err, result) { ... } );更多推荐
MongoDB 投影参数在 findOne() 中不起作用
发布评论