且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-14 09:59:05

来自 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 } )

在 Mongo 的这个例子中,返回的文档将只包含 itemqty_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.students.find({}, {roll:1, _id:0})

上述语句将选择students集合中的所有文档,返回的文档将只返回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"字段.所以我们需要明确提到 _id:0roll.

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.