如何为 MongoDB 集合中的所有文档选择单个字段? [英] How to select a single field for all documents in a MongoDB collection?

查看:27
本文介绍了如何为 MongoDB 集合中的所有文档选择单个字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

在 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.

这篇关于如何为 MongoDB 集合中的所有文档选择单个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆