在我的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

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


当前回答

这对我很有用,

db.student.find({},{"roll":1})

where子句中没有条件,即在第一个花括号内。 下一个花括号内:结果中需要的投影字段名称列表,1表示特定字段是查询结果的一部分

其他回答

 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);
        });
      });  

它的工作

使用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

在mongodb 3.4中,我们可以使用下面的逻辑,我不确定以前的版本

Select roll from student ==> db.student.find(!{}, {1}):

上面的逻辑有助于定义一些列(如果它们更少的话)

从表中获取所有数据

db.student.find({})

SELECT * FROM student


从没有_id的表中获取所有数据

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

SELECT name, roll FROM student


从_id字段中获取所有数据

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

SELECT id, roll FROM student


从一个没有_id的字段中获取所有数据

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

从学生中选择卷


使用where子句查找指定的数据

db.student.find({roll: 80})

SELECT * FROM student WHERE roll = '80'


使用where子句和大于条件查找数据

db.student.find({ "roll": { $gt: 70 }}) // $gt is greater than 

SELECT * FROM student WHERE roll > '70'


使用where子句和大于或等于condition查找数据

db.student.find({ "roll": { $gte: 70 }}) // $gte is greater than or equal

SELECT * FROM student WHERE >= '70'


使用where子句和小于或等于condition查找数据

db.student.find({ "roll": { $lte: 70 }}) // $lte is less than or equal

SELECT * FROM student WHERE roll <= '70'


使用where子句和小于to条件查找数据

db.student.find({ "roll": { $lt: 70 }})  // $lt is less than

SELECT student WHERE roll < '70'

虽然gowtham的回答是完整的,但值得注意的是,这些命令可能会因API的不同而不同(对于那些不使用mongo的shell的人来说)。 详细信息请参考文档链接。

例如,Nodejs有一个叫做投影的方法,你可以把它附加到你的find函数中来进行投影。

按照相同的示例设置,可以在Node中使用如下命令:

db.student.find ({}) . project({卷:1})

SELECT _id, rollfrom student

或 db.student.find({})。项目({roll:1, _id: 0})

从学生中选择卷

等等。

同样,对于nodejs用户,不要忘记(如果你以前使用过这个API,你应该已经熟悉了)使用toArray来附加你的.then命令。