MongoDB 投影参数在 findOne() 中不起作用

编程入门 行业动态 更新时间:2024-10-24 14:17:21
本文介绍了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() 中不起作用

本文发布于:2023-11-22 13:08:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617537.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中不   参数   MongoDB   findOne

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!