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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25589113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:09:00  来源:igfitidea点击:

How to select a single field for all documents in a MongoDB collection?

mongodbprojection

提问by Shipra Swati

In my MongoDB, I have a student collection with 10 records having fields nameand roll. One record of this collection is:

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

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

I want to retrieve the field rollonly for all 10 records in the collection as we would do in traditional database by using:

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

SELECT roll FROM student

I went through many blogs but all are resulting in a query which must have WHEREclause in it, for example:

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

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

The query is equivalent to:

该查询等效于:

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.

我的要求是在没有任何条件的情况下只找到一个密钥。那么,它的查询操作是什么。

回答by therealrootuser

From the MongoDB docs:

来自MongoDB 文档

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

一个投影可以明确地包含多个字段。在以下操作中, find() 方法返回与查询匹配的所有文档。在结果集中,只有 item 和 qty 字段以及默认情况下 _id 字段在匹配文档中返回。

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

In this example from the folks at Mongo, the returned documents will contain only the fields of item, qty, and _id.

在从蒙戈的乡亲这个例子中,返回的文档将只包含的领域itemqty_id



Thus, you should be able to issue a statement such as:

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

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

The above statement will select all documents in the students collection, and the returned document will return only the rollfield (and exclude the _id).

上述语句将选择学生集合中的所有文档,返回的文档将仅返回roll字段(并排除_id)。

If we don't mention _id:0the fields returned will be rolland _id. The '_id' field is always displayed by default. So we need to explicitly mention _id:0along with roll.

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

回答by Gowtham Sooryaraj

get all data from table

从表中获取所有数据

db.student.find({})

SELECT * FROM student

选择 * 从学生



get all data from table without _id

从没有_id的表中获取所有数据

db.student.find({}, {_id:0})

SELECT name, roll FROM student

选择姓名,从学生中滚动



get all data from one field with _id

使用 _id 从一个字段中获取所有数据

db.student.find({}, {roll:1})

SELECT id, roll FROM student

选择 ID,从学生中滚动



get all data from one field without _id

从没有_id的字段中获取所有数据

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

SELECT roll FROM student

从学生中选择卷



find specified data using where clause

使用 where 子句查找指定数据

db.student.find({roll: 80})

SELECT * FROM students WHERE roll = '80'

SELECT * FROM Students WHERE roll = '80'



find a data using where clause and greater than condition

使用 where 子句和大于条件查找数据

db.student.find({ "roll": { $gt: 70 }}) // $gt is greater than 

SELECT * FROM student WHERE roll > '70'

SELECT * FROM student WHERE roll > '70'



find a data using where clause and greater than or equal to condition

使用 where 子句和大于或等于条件查找数据

db.student.find({ "roll": { $gte: 70 }}) // $gte is greater than or equal

SELECT * FROM student WHERE roll >= '70'

SELECT * FROM student WHERE roll >= '70'



find a data using where clause and less than or equal to condition

使用 where 子句和小于或等于条件查找数据

db.student.find({ "roll": { $lte: 70 }}) // $lte is less than or equal

SELECT * FROM student WHERE roll <= '70'

SELECT * FROM student WHERE roll <= '70'



find a data using where clause and less than to condition

使用 where 子句和小于条件查找数据

db.student.find({ "roll": { $lt: 70 }})  // $lt is less than

SELECT * FROM student WHERE roll < '70'

SELECT * FROM student WHERE roll <'70'



回答by grepit

I think mattingly890 has the correct answer , here is another example along with the pattern/commmand

我认为 mattingly890 有正确的答案,这是另一个例子以及模式/命令

db.collection.find( {}, {your_key:1, _id:0})

db.collection.find( {}, {your_key:1, _id:0})

enter image description here

在此处输入图片说明

回答by Vivek Doshi

Here you go , 3 ways of doing , Shortestto boring :

给你,3 种方法,最短到无聊:

db.student.find({}, 'roll _id'); // <--- Just multiple fields name space separated
// OR
db.student.find({}).select('roll _id'); // <--- Just multiple fields name space separated
// OR
db.student.find({}, {'roll' : 1 , '_id' : 1 ); // <---- Old lengthy boring way

To removespecific field use -operator :

删除特定字段使用-运算符:

db.student.find({}).select('roll -_id') // <--- Will remove id from result

回答by Vaggelis Stefanakis

Just for educational purposes you could also do it with any of the following ways:

仅出于教育目的,您还可以通过以下任何一种方式进行操作:

1.

1.

    var query = {"roll": {$gt: 70};
    var cursor = db.student.find(query);
    cursor.project({"roll":1, "_id":0});

2.

2.

    var query = {"roll": {$gt: 70};
    var projection = {"roll":1, "_id":0};
    var cursor = db.student.find(query,projection);

`

`

回答by Karan Khanna

Try the following query:

尝试以下查询:

db.student.find({}, {roll: 1, _id: 0}).pretty();

Hope this helps!!

希望这可以帮助!!

回答by Smily

While gowtham's answeris complete, it is worth noting that those commands may differ from on API to another (for those not using mongo's shell).
Please refer to documentation linkfor detailed info.

虽然gowtham 的回答是完整的,但值得注意的是,这些命令可能因 API 的不同而不同(对于那些不使用 mongo 的 shell 的命令)。有关详细信息,
请参阅文档链接

Nodejs, for instance, have a method called `projection that you would append to your find function in order to project.

例如,Nodejs有一个名为“projection”的方法,您可以将其附加到您的 find 函数中以进行投影。

Following the same example set, commands like the following can be used with Node:

遵循相同的示例集,类似以下的命令可以与 Node 一起使用:

db.student.find({}).project({roll:1})

db.student.find({}).project({roll:1})

SELECT _id, roll FROM student

SELECT _id,从学生滚动

Or
db.student.find({}).project({roll:1, _id: 0})

或者
db.student.find({}).project({roll:1, _id: 0})

SELECT roll FROM student

从学生中选择卷

and so on.

等等。

Again for nodejs users, do not forget (what you should already be familiar with if you used this API before) to use toArrayin order to append your .thencommand.

再次对于 nodejs 用户,不要忘记(如果您之前使用过这个 API,您应该已经熟悉的内容)toArray用于附加您的.then命令。

回答by Anthony Awuley

db.<collection>.find({}, {field1: <value>, field2: <value> ...})

In your example, you can do something like:

在您的示例中,您可以执行以下操作:

db.students.find({}, {"roll":true, "_id":false})

Projection

投影

The projection parameter determines which fields are returned in the matching documents. The projection parameter takes a document of the following form:

投影参数确定在匹配文档中返回哪些字段。投影参数采用以下形式的文档:

{ field1: <value>, field2: <value> ... }
The <value> can be any of the following:
  1. 1 or true to include the field in the return documents.

  2. 0 or false to exclude the field.

The <value> can be any of the following:
  1. 1 或 true 以在返回文档中包含该字段。

  2. 0 或 false 以排除该字段。

NOTE

笔记

For the _id field, you do not have to explicitly specify _id: 1 to return the _id field. The find() method always returns the _id field unless you specify _id: 0 to suppress the field.

对于 _id 字段,您不必显式指定 _id: 1 即可返回 _id 字段。find() 方法总是返回 _id 字段,除非您指定 _id: 0 来取消该字段。

READ MORE

阅读更多

回答by Hasib Kamal

For better understanding I have written similar MySQL query.

为了更好地理解,我编写了类似的 MySQL 查询。

Selecting specific fields 

MongoDB :db.collection_name.find({},{name:true,email:true,phone:true});

MySQL :SELECT name,email,phone FROM table_name;

MongoDB :db.collection_name.find({},{name:true,email:true,phone:true});

MySQL :SELECT name,email,phone FROM table_name;

Selecting specific fields with where clause

MongoDB :db.collection_name.find({email:'[email protected]'},{name:true,email:true,phone:true});

MySQL :SELECT name,email,phone FROM table_name WHERE email = '[email protected]';

MongoDB :db.collection_name.find({email:'[email protected]'},{name:true,email:true,phone:true});

MySQL :SELECT name,email,phone FROM table_name WHERE email = '[email protected]';

回答by Aishwarya Panchal

This works for me,

这对我有用,

db.student.find({},{"roll":1})

no condition in where clause i.e., inside first curly braces. inside next curly braces: list of projection field names to be needed in the result and 1 indicates particular field is the part of the query result

where 子句中没有条件,即在第一个花括号内。下一个大括号内:结果中需要的投影字段名​​称列表,1表示特定字段是查询结果的一部分