在我的MongoDB中,我有一个学生集合,其中有10条记录,字段为name和roll。这个收藏的一个记录是:

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

我想检索字段滚动仅为集合中的所有10条记录,因为我们会在传统数据库中使用:

SELECT roll FROM student

我浏览了很多博客,但所有的结果都是一个必须有WHERE子句的查询,例如:

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

查询等价于:

SELECT * FROM student WHERE roll > 70

我的要求是只找到一个钥匙,不附带任何条件。它的查询操作是什么。


当前回答

给你,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

删除特定字段的使用-操作符:

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

其他回答

来自MongoDB文档:

投影可以显式地包括几个字段。在接下来的操作中,find()方法返回与查询匹配的所有文档。在结果集中,匹配的文档中只返回item和qty字段,默认情况下,返回_id字段。 db.inventory。查找({类型:'食物'},{项目:1,数量:1})

在这个来自Mongo的例子中,返回的文档将只包含item、qty和_id字段。


因此,你应该能够发出这样的声明:

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

上面的语句将选择students集合中的所有文档,返回的文档将只返回roll字段(不包括_id)。

如果我们不提到_id:0,返回的字段将是roll和_id。默认情况下总是显示'_id'字段。因此,我们需要显式地提到_id:0和roll。

得到学生的名字

student-details = db.students.find({{ "roll": {$gt: 70} },{"name": 1, "_id": False})

获取学生的姓名和名单

student-details = db.students.find({{ "roll": {$gt: 70}},{"name": 1,"roll":1,"_id": False})

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

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

> db.mycollection.find().pretty();

{
    "_id": ObjectId("54ffca63cea5644e7cda8e1a"),
    "host": "google",
    "ip": "1.1.192.1"
}
db.mycollection.find({},{ "_id": 0, "host": 1 }).pretty();

如果你在NodeJs中使用MongoDB驱动程序,那么上述答案可能不适合你。您将不得不执行类似的操作,以仅获得选定的属性作为响应。

import { MongoClient } from "mongodb";

// Replace the uri string with your MongoDB deployment's connection string.
const uri = "<connection string uri>";
const client = new MongoClient(uri);

async function run() {
  try {
    await client.connect();
    const database = client.db("sample_mflix");
    const movies = database.collection("movies");

    // Query for a movie that has the title 'The Room'
    const query = { title: "The Room" };

    const options = {
      // sort matched documents in descending order by rating
      sort: { "imdb.rating": -1 },
      // Include only the `title` and `imdb` fields in the returned document
      projection: { _id: 0, title: 1, imdb: 1 },
    };

    const movie = await movies.findOne(query, options);

    /** since this method returns the matched document, not a cursor, 
     * print it directly 
    */
    console.log(movie);
  } finally {
    await client.close();
  }
}

run().catch(console.dir);

这段代码是从实际的MongoDB文档中复制的,你可以在这里查看。 https://docs.mongodb.com/drivers/node/current/usage-examples/findOne/

我只是想在答案中补充一点,如果想要显示嵌套在另一个对象中的字段,可以使用以下语法

db.collection。查找({},{{'对象。关键的:真}})

Here键存在于名为object的对象中

{ "_id" : ObjectId("5d2ef0702385"), "object" : { "key" : "value" } }