在我的 MongoDB 中,我有一个包含 10 条记录的学生集合,其中包含字段 name
和 roll
。该集合的一条记录是:
{
"_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 的示例中,返回的文档将仅包含 item
、qty
和 _id
字段。
因此,您应该能够发出如下声明:
db.students.find({}, {roll:1, _id:0})
上面的语句会选择students集合中的所有文档,返回的文档只会返回roll
字段(并排除_id
)。
如果我们不提及 _id:0
,则返回的字段将是 roll
和 _id
。默认情况下始终显示“_id”字段。所以我们需要明确提到 _id:0
和 roll
。
关于mongodb - 如何为 MongoDB 集合中的所有文档选择单个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25589113/