如何为MongoDB集合中的所有文档选择单个字段? [英] How to select a single field for all documents in a MongoDB collection?
问题描述
在我的MongoDB中,我有一个学生集合,其中包含10个记录,其字段分别为name
和roll
.此收藏的一条记录是:
In my MongoDB, I have a student collection with 10 records having fields name
and roll
. One record of this collection is:
{
"_id" : ObjectId("53d9feff55d6b4dd1171dd9e"),
"name" : "Swati",
"roll" : "80",
}
我想只对集合中的所有10条记录检索字段roll
,就像我们在传统数据库中使用的那样:
I want to retrieve the field roll
only for all 10 records in the collection as we would do in traditional database by using:
SELECT roll FROM student
我浏览了许多博客,但所有博客都导致一个查询,其中必须包含WHERE
子句,例如:
I went through many blogs but all are resulting in a query which must have WHERE
clause in it, for example:
db.students.find({ "roll": { $gt: 70 })
查询等同于:
SELECT * FROM student WHERE roll > 70
我的要求是仅找到一个没有任何条件的钥匙.那么,对此的查询操作是什么.
My requirement is to find a single key only without any condition. So, what is the query operation for that.
推荐答案
来自 MongoDB文档:
投影可以明确包含几个字段.在以下操作中,find()方法返回与查询匹配的所有文档.在结果集中,只有item和qty字段以及默认情况下_id字段返回到匹配的文档中.
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})
db.inventory.find( { type: 'food' }, { item: 1, qty: 1 } )
在此示例中,来自Mongo的同事们,返回的文档将仅包含item
,qty
和_id
字段.
In this example from the folks at Mongo, the returned documents will contain only the fields of item
, qty
, and _id
.
因此,您应该可以发出如下声明:
Thus, you should be able to issue a statement such as:
db.student.find({}, {roll:1, _id:0})
以上语句将选择学生集合中的所有文档,并且返回的文档将仅返回roll
字段(不包括_id
).
The above statement will select all documents in the students collection, and the returned document will return only the roll
field (and exclude the _id
).
如果我们不提及_id:0
,则返回的字段将是roll
和_id
.默认情况下始终显示"_id"字段.因此,我们需要与roll
一起明确提及_id:0
.
If we don't mention _id:0
the fields returned will be roll
and _id
. The '_id' field is always displayed by default. So we need to explicitly mention _id:0
along with roll
.
这篇关于如何为MongoDB集合中的所有文档选择单个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!