在我的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

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


当前回答

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

例如,Nodejs有一个叫做投影的方法,你可以把它附加到你的find函数中来进行投影。

按照相同的示例设置,可以在Node中使用如下命令:

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

SELECT _id, rollfrom student

或 db.student.find({})。项目({roll:1, _id: 0})

从学生中选择卷

等等。

同样,对于nodejs用户,不要忘记(如果你以前使用过这个API,你应该已经熟悉了)使用toArray来附加你的.then命令。

其他回答

尝试以下查询:

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

如果你正在使用控制台,你可以添加pretty()使其易于阅读。

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

希望这能有所帮助!!

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

例如,Nodejs有一个叫做投影的方法,你可以把它附加到你的find函数中来进行投影。

按照相同的示例设置,可以在Node中使用如下命令:

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

SELECT _id, rollfrom student

或 db.student.find({})。项目({roll:1, _id: 0})

从学生中选择卷

等等。

同样,对于nodejs用户,不要忘记(如果你以前使用过这个API,你应该已经熟悉了)使用toArray来附加你的.then命令。

如果你在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" } }

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

Selecting specific fields 

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

Selecting specific fields with where clause

MongoDB: db.collection_name.find({email:'you@email.com'},{name:true,email:true,phone:true}); SELECT name,email,phone FROM table_name WHERE email = 'you@email.com';