【问题标题】:NodeJS mongo driver find statement with projection returning full documentNodeJS mongo 驱动程序查找语句,投影返回完整文档
【发布时间】:2018-01-13 01:05:05
【问题描述】:

我有以下功能仅从info 集合中过滤order_id。 而不是得到_idorder_id 回调是从数据库中获取所有键值。 节点版本:9.4 Mongo 版本:3.4

var listCollections=function (columns,db,callback) {
    if (columns.length===0) {
        return callback('No columns specified')
    }
    columns.forEach(function (col) {
        query[col]=true;
    });
    db.collection('info').find({},{order_id:true}).toArray(function (mongoError,result) {
        console.log(result);
    });
};

请在这里纠正我,但就 mongo 驱动程序的文档而言,我的语法是正确的。 如何从集合中只获取指定的列?

【问题讨论】:

  • 您能否发布您正在使用的文档的链接?
  • 我指的是link
  • 该链接适用于驱动程序 v1.4.9。你确定你用的是这个版本?与mongo 3.4兼容的驱动最早版本是2.2.12:docs.mongodb.com/ecosystem/drivers/…
  • @AlexBlex 它的 3.0.1。感谢您指出版本不匹配。

标签: node.js mongodb


【解决方案1】:

find Collection 方法在 nodejs 驱动程序中接受单个参数 - 查询本身。

projection 应用于光标:

db.collection('info')
  .find({})
  .project({order_id:1})
  .toArray(function (mongoError,result) {
    console.log(result);
  });

【讨论】:

【解决方案2】:

使用“字段”选项。

**db.collection('info').find({},{fields:{_id:0,name:1}}).toArray(function (mongoError,result) {
        console.log(result);
    })**

【讨论】:

    猜你喜欢
    • 2016-10-09
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多