Find Multiple Documents查找多个文档¶
You can query for multiple documents in a collection with 可以使用collection.find()
. collection.find()
查询集合中的多个文档。The find()
method uses a query document that you provide to match the subset of the documents in the collection that match the query. find()
方法使用您提供的查询文档来匹配集合中与查询匹配的文档子集。If you don't provide a query document (or if you provide an empty document), MongoDB returns all documents in the collection. 如果不提供查询文档(或提供空文档),MongoDB将返回集合中的所有文档。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 result set. 还可以定义其他查询选项(如排序和投影)来配置结果集。You can specify these in the options parameter in your 您可以在find()
method call in sort
and projection
objects. sort
和projection
对象中的find()
方法调用中的options
参数中指定这些。See collection.find() for more information on the parameters you can pass to the method.有关可以传递给方法的参数的更多信息,请参阅collection.find()
。
The find()
method returns a FindCursor that manages the results of your query. find()
方法返回管理查询结果的FindCursor。You can iterate through the matching documents using one of the following cursor methods:您可以使用以下游标方法之一遍历匹配的文档:
next()
toArray()
forEach()
If no documents match the query, 如果没有与查询匹配的文档,find()
returns an empty cursor.find()
将返回一个空游标。
Example示例¶
The following snippet finds documents from the 以下代码段从movies
collection. movies
集合中查找文档。It uses the following parameters:它使用以下参数:
A query document that configures the query to return only movies with a runtime of less than 15 minutes.将查询配置为仅返回运行时间小于15分钟的电影的查询文档。A sort that organizes returned documents in ascending order by title (alphabetical order in which "A" comes before "Z" and "1" before "9").一种按标题升序(字母顺序,其中“A”在“Z”之前,“1”在“9”之前)组织返回文档的排序。A projection that explicitly excludes the一种投影,从返回的文档中明确排除_id
field from returned documents and explicitly includes only thetitle
andimdb
object (and its embedded fields)._id
字段,只明确包括title
和imdb
对象(及其嵌入字段)。
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 movies that have a runtime less than 15 minutes查询运行时间少于15分钟的电影
const query = { runtime: { $lt: 15 } };
const options = {
// sort returned documents in ascending order by title (A->Z)按标题(A->Z)升序对返回的文档进行排序
sort: { title: 1 },
// Include only the `title` and `imdb` fields in each returned document在每个返回的文档中仅包括“title”和“imdb”字段
projection: { _id: 0, title: 1, imdb: 1 },
};
const cursor = movies.find(query, options);
// print a message if no documents were found如果未找到任何文档,则打印消息
if ((await cursor.count()) === 0) {
console.log("No documents found!");
}
// replace console.dir with your callback to access individual elements用回调替换console.dir以访问单个元素
await cursor.forEach(console.dir);
} 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);
type Minutes = number;
interface IMDB {
rating: number;
votes: number;
id: number;
}
interface Movie {
title: string;
imdb: IMDB;
runtime: Minutes;
}
async function run() {
try {
await client.connect();
const database = client.db("sample_mflix");
const movies = database.collection<Movie>("movies");
const cursor = movies.find<Movie>(
{ runtime: { $lt: 15 } },
{
sort: { title: 1 },
projection: { _id: 0, title: 1, imdb: 1 },
}
);
if ((await cursor.count()) === 0) {
console.warn("No documents found!");
}
await cursor.forEach(console.dir);
} finally {
await client.close();
}
}
run().catch(console.dir);
If you run the preceding example, you should see the following output:如果运行前面的示例,您应该会看到以下输出:
{ title: '10 Minutes', imdb: { rating: 7.9, votes: 743, id: 339976 } }
{ title: '3x3', imdb: { rating: 6.9, votes: 206, id: 1654725 } }
{ title: '7:35 in the Morning', imdb: { rating: 7.3, votes: 1555, id: 406501 } }
{ title: '8', imdb: { rating: 7.8, votes: 883, id: 1592502 } }
...
The sort
and projection
options can also be specified as methods (sort()
and project()
, respectively) chained to the findOne
method. srt
和projection
选项也可以指定为链接到findOne方法的方法(分别是sort()
和project()
。The following two commands are equivalent:以下两个命令是等效的:
collection.find({ runtime: { $lt: 15 } },
{
sort: { title: 1 },
projection: { _id: 0, title: 1, imdb: 1 }
});
collection.find({ runtime: { $lt: 15 } })
.sort({ title: 1})
.project({ _id: 0, title: 1, imdb: 1 });