查找文档
您可以使用以下命令在集合中查询单个文档:collection.findOne()
方法。该 findOne()
方法使用你提供的查询文档来匹配集合中符合查询条件的文档子集。如果你没有提供查询文档或提供的文档为空,MongoDB 将匹配集合中的所有文档。findOne()
操作只返回第一个匹配的文档。有关查询 MongoDB 的更多信息,请参阅我们的关于查询文档的文档.
你还可以定义更多查询选项,例如 排序 和 投影 来配置返回的文档。你可以在 findOne
方法的第二个参数中传递的 options
对象中指定更多选项。有关详细的参考文档,请参阅collection.findOne().
兼容性
你可以使用 Node.js 驱动来连接并使用 findOne()
方法在以下环境中部署
MongoDB Atlas:云中 MongoDB 部署的全托管服务
MongoDB Enterprise:基于订阅的、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用并自我管理的 MongoDB 版本
要了解更多关于在 MongoDB Atlas 中查找文档的信息请参阅 创建、查看、更新和删除文档。
示例
以下代码片段从 movies
集合中查找单个文档。它使用了以下参数
查询文档,配置查询以返回标题恰好为文本
'The Room'
的电影。一种对匹配文档按评分从高到低进行排序的 排序 ,因此如果我们的查询匹配多个文档,则返回的文档将是评分最高的文档。
一种 投影 ,明确排除返回文档中的
_id
字段,并明确仅包含title
和imdb
对象(及其嵌套字段)。
注意
您可以使用此示例连接到MongoDB实例并交互一个包含样本数据的数据库。要了解有关连接到您的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 { // Get the database and collection on which to run the operation 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 }, }; // Execute query const movie = await movies.findOne(query, options); // Print the document returned by findOne() 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. 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 { 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);
运行前面的示例,您将看到以下输出
{ title: 'The Room', imdb: { rating: 3.5, votes: 25673, id: 368226 } }