【问题标题】:How to only field names(not field values) of a particular document using node.js [duplicate]如何使用node.js仅字段名称(不是字段值)
【发布时间】:2018-04-30 11:16:29
【问题描述】:

我是 MongoDB 和 node.js 的初学者。实际上,我正在尝试获取特定文档的名称,但我想知道该怎么做。 让我详细说明: 如果“a”是一个包含名为“student”的文档的集合,并且“student”包含像

这样的字段
{
    "_id: "student",
    "name": "alex",
    "roll": "3",
    "age":"13"
} 

那么如何获取["name","roll","age"]格式的字段名 通过尝试:

db.collection("user").find({ "_id": "student" }).toArray(function(err, result) {
    console.log(result)
})

为所有字段提供它们的值。

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    尝试:

    db.collection("user").find({"_id":"student"}, {name:1}).toArray(function(err, result) {console.log(result)}

    如果您想排除字段:

    db.collection("user").find({"_id":"student"}, {roll:0, age:0}).toArray(function(err, result) {console.log(result)}

    【讨论】:

      【解决方案2】:

      这将起作用:

      db.collection("user",function(err,user){
         var array = [];
         user.findOne(function(err,doc){
           for (key in doc) array.push(key);
         });
         console.log(array);
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-08
        • 2019-10-24
        相关资源
        最近更新 更多