Find a Document查找一个文档

Note

If you specify a callback method, findOne() returns nothing. 如果指定回调方法,findOne()将不返回任何内容。If you do not specify one, this method returns a Promise that resolves to the result object when it completes. 如果未指定,此方法将返回一个Promise,该Promise在完成时解析为结果对象。See our guide on Promises and Callbacks for more information, or the API documentation for information on the result object.有关更多信息,请参阅我们的承诺和回调指南,或参阅API文档以了解有关输出对象的信息。

You can query for a single document in a collection with the collection.findOne() method. 可以使用collection.findOne()方法查询集合中的单个文档。The findOne() method uses a query document that you provide to match only the subset of the documents in the collection that match the query. findOne()方法使用您提供的查询文档,仅匹配集合中与查询匹配的文档子集。If you don't provide a query document or if you provide an empty document, MongoDB matches all documents in the collection. 如果不提供查询文档或提供空文档,MongoDB将匹配集合中的所有文档。The findOne() operation only returns the first matched document. findOne()操作只返回第一个匹配的文档。For more information on querying MongoDB, see our documentation on query documents.有关查询MongoDB的更多信息,请参阅我们关于查询文档的文档

You can also define additional query options such as sort and projection to configure the returned document. 还可以定义其他查询选项(如排序投影)来配置返回的文档。You can specify the additional options in the options object passed as the second parameter of the findOne method. 您可以在作为findOne方法的第二个参数传递的options对象中指定其他选项。For detailed reference documentation, see collection.findOne().有关详细的参考文档,请参阅collection.findOne()

The following snippet finds a single document from the movies collection. 以下代码段从movies集合中查找单个文档。It uses the following parameters:它使用以下参数:

  • A query document that configures the query to return only movies with the title of exactly the text 'The Room'.一个查询文档,将查询配置为仅返回标题为'The Room'的电影。
  • A sort that organizes matched documents in descending order by rating, so if our query matches multiple documents the returned document will be the document with the highest rating.一种按评级按降序排列匹配文档的排序,因此如果查询匹配多个文档,则返回的文档将是评级最高的文档。
  • A projection that explicitly excludes the _id field from returned documents and explicitly includes only the title and imdb object (and its embedded fields).一种投影,从返回的文档中明确排除_id字段,只明确包括titleimdb对象(及其嵌入字段)。
Note

You can use this example to connect to an instance of MongoDB and interact with a database that contains sample data. 您可以使用此示例连接到MongoDB实例,并与包含示例数据的数据库交互。To learn more about connecting to your MongoDB instance and loading a sample dataset, see the Usage Examples guide.要了解有关连接到MongoDB实例并加载示例数据集的更多信息,请参阅用法示例指南

import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.用MongoDB部署的连接字符串替换uri字符串。 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'查询标题为“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在返回的文档中仅包括“title”和“imdb”字段 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);
import { MongoClient } from "mongodb";
// Replace the uri string with your MongoDB deployment's connection string.用MongoDB部署的连接字符串替换uri字符串。 const uri = "<connection string uri>";
const client = new MongoClient(uri);
interface IMDB { rating: number; votes: number; id: number; }
export interface Movie { title: string; year: number; released: Date; plot: string; type: "movie" | "series"; imdb: IMDB; }
type MovieSummary = Pick<Movie, "title" | "imdb">;
async function run(): Promise<void> { try { await client.connect();
const database = client.db("sample_mflix"); // Specifying a Schema is always optional, but it enables type hinting on finds and inserts指定架构始终是可选的,但它在查找和插入时启用类型暗示 const movies = database.collection<Movie>("movies");
const movie = await movies.findOne<MovieSummary>( { title: "The Room" }, { sort: { rating: -1 }, projection: { _id: 0, title: 1, imdb: 1 }, } ); console.log(movie); } finally { await client.close(); } } run().catch(console.dir);

If you run the preceding example, you should see the following output:如果运行前面的示例,您应该会看到以下输出:

{ title: 'The Room', imdb: { rating: 3.5, votes: 25673, id: 368226 } }