Docs 菜单
Docs 主页
/ / /
Node.js
/ /

查找文档

您可以使用 collection.findOne()方法查询集合中的单个文档。 findOne()方法使用您提供的查询文档仅匹配集合中与查询匹配的文档子集。如果未提供查询文档或提供空文档,MongoDB 将匹配集合中的所有文档。 findOne()操作仅返回第一个匹配的文档。有关查询 MongoDB 的更多信息,请参阅有关查询文档的文档。

您还可以定义其他查询选项(例如 排序 和 投影 )来配置返回的文档。您可以在作为options 方法的第二个参数传递的findOne 对象中指定其他选项。有关详细的参考文档,请参阅 collection.findOne()。

您可以使用 Node.js 驱动程序连接到以下环境中托管的部署并对其使用 findOne() 方法:

  • MongoDB Atlas :用于在云中部署 MongoDB 的完全托管服务

  • MongoDB Enterprise:基于订阅、自行管理的 MongoDB 版本

  • MongoDB Community:source-available、免费使用且可自行管理的 MongoDB 版本

要了解有关在 Atlas 用户界面中为 MongoDB Atlas 托管的部署查找文档的更多信息,请参阅创建、查看、更新和删除文档

以下代码段查找 movies 集合中的单个文档。它使用以下参数:

  • 一个查询文档,用于配置查询,仅返回标题与文本 'The Room' 完全相同的电影。

  • 一种排序方式,它可按评分降序排列匹配的文档;因此,如果查询能匹配多个文档,返回的文档则是评分最高的文档。

  • 一个投影,它会从返回的文档中显式排除 _id 字段并显式仅包含 titleimdb 对象(及其嵌入式字段)。

注意

可以使用此示例连接到 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 } }

后退

查找操作