在我的MongoDB中,我有一个学生集合,其中有10条记录,字段为name和roll。这个收藏的一个记录是:

{
    "_id" : ObjectId("53d9feff55d6b4dd1171dd9e"),
    "name" : "Swati",
    "roll" : "80",
}

我想检索字段滚动仅为集合中的所有10条记录,因为我们会在传统数据库中使用:

SELECT roll FROM student

我浏览了很多博客,但所有的结果都是一个必须有WHERE子句的查询,例如:

db.students.find({ "roll": { $gt: 70 })

查询等价于:

SELECT * FROM student WHERE roll > 70

我的要求是只找到一个钥匙,不附带任何条件。它的查询操作是什么。


当前回答

 var collection = db.collection('appuser');
    collection.aggregate(
      { $project : { firstName : 1, lastName : 1 } },function(err, res){
        res.toArray(function(err, realRes){
          console.log("response roo==>",realRes);
        });
      });  

它的工作

其他回答

尝试以下查询:

db.student.find({}, {roll: 1, _id: 0});

如果你正在使用控制台,你可以添加pretty()使其易于阅读。

db.student.find({}, {roll: 1, _id: 0}).pretty();

希望这能有所帮助!!

得到学生的名字

student-details = db.students.find({{ "roll": {$gt: 70} },{"name": 1, "_id": False})

获取学生的姓名和名单

student-details = db.students.find({{ "roll": {$gt: 70}},{"name": 1,"roll":1,"_id": False})

查询MongoDB这里的费用是收集和描述是一个字段。

db.getCollection('fees').find({},{description:1,_id:0})

使用Studio 3T for MongoDB,如果我使用.find({}, {_id: 0, roll: true}),它仍然返回一个带有空_id属性的对象数组。

使用JavaScript map帮助我只检索所需的滚动属性作为字符串数组:

var rolls = db.student
  .find({ roll: { $gt: 70 } }) // query where role > 70
  .map(x => x.roll);           // return an array of role
db.<collection>.find({}, {field1: <value>, field2: <value> ...})

在你的例子中,你可以这样做:

db.students.find({}, {"roll":true, "_id":false})

投影

类型中返回哪些字段 匹配的文件。类型的文档为参数 下面的形式:

{ field1: <value>, field2: <value> ... }

<值>可以是以下任意值: 1或true表示在返回文档中包含该字段。 0或false排除该字段。

NOTE

对于_id字段,您不必显式地指定_id: 1到 返回_id字段。find()方法总是返回_id字段 除非指定_id: 0来屏蔽该字段。

阅读更多