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

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


当前回答

 var collection = db.collection('appuser');
    collection.aggregate(
      { $project : { firstName : 1, lastName : 1 } },function(err, res){
        res.toArray(function(err, realRes){
          console.log("response roo==>",realRes);
        });
      });  

它的工作

其他回答

出于教育目的,你也可以用以下任何一种方法:

1.

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

2.

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

`

我认为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();

除了人们已经提到的,我只是在混合中引入索引。

假设有一个很大的集合,假设有超过100万个文档,你必须运行这样的查询。

WiredTiger内部缓存将不得不保持所有的数据在缓存中,如果你必须运行这个查询,如果不是数据将被馈送到WT内部缓存从FS缓存或磁盘从DB检索之前完成(批量如果被调用从连接到数据库的驱动程序&给定100万文档不返回在1走,光标起作用)

覆盖的查询可以是另一种选择。直接从文档中复制文本。

当一个索引覆盖一个查询时,MongoDB既可以匹配查询条件,又可以只使用索引键返回结果;即MongoDB不需要检查集合中的文档来返回结果。

当索引涵盖查询时,解释结果具有一个IXSCAN阶段,该阶段不是FETCH阶段的后代,并且在executionStats中,totaldocsexamining为0。

Query :  db.getCollection('qaa').find({roll_no : {$gte : 0}},{_id : 0, roll_no : 1})

Index : db.getCollection('qaa').createIndex({roll_no : 1})

如果这里的索引在WT内部缓存中,那么获取值将是一个简单的过程。索引对系统的写性能有影响,因此,如果读的数量比写的数量多,这就更有意义了。

在mongodb 3.4中,我们可以使用下面的逻辑,我不确定以前的版本

Select roll from student ==> db.student.find(!{}, {1}):

上面的逻辑有助于定义一些列(如果它们更少的话)

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