mongodb - 如何为 MongoDB 集合中的所有文档选择单个字段?

标签 mongodb projection mongo-collection

在我的 MongoDB 中,我有一个包含 10 条记录的学生集合,其中包含字段 nameroll。该集合的一条记录是:

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

我想只为集合中的所有 10 条记录检索字段 roll,就像我们在传统数据库中使用的那样:

SELECT roll FROM student

我浏览了很多博客,但都导致查询中必须包含 WHERE 子句,例如:

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

查询相当于:

SELECT * FROM student WHERE roll > 70

我的要求是只找到一个没有任何条件的键。那么,查询操作是什么。

最佳答案

来自 MongoDB docs :

A projection can explicitly include several fields. In the following operation, find() method returns all documents that match the query. In the result set, only the item and qty fields and, by default, the _id field return in the matching documents.

db.inventory.find( { type: 'food' }, { item: 1, qty: 1 } )

在这个来自 Mongo 的示例中,返回的文档将仅包含 itemqty_id 字段。


因此,您应该能够发出如下声明:

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

上面的语句会选择students集合中的所有文档,返回的文档只会返回roll字段(并排除_id)。

如果我们不提及 _id:0,则返回的字段将是 roll_id。默认情况下始终显示“_id”字段。所以我们需要明确提到 _id:0roll

关于mongodb - 如何为 MongoDB 集合中的所有文档选择单个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25589113/

相关文章:

mongodb - Mongodb cursor Finalizer Enabled性能效果

java - 注册-Spring Boot-MongoDb-主键替换新数据

javascript - OpenLayers: map 无法使用非 'standard' EPSG 代码进行渲染

grails - grails服务功能的返回类型是什么?

sql - 这个投影会返回什么?

MongoDB 查找算法复杂度

javascript - 在 mongodb 中不显示 $Sum 输出

使用 Monger 的 MongoDB 连接模式

node.js - mongo-connect(session) 的 mongo-connect 错误