Docs Menu
Docs Home
/ / /
Node.js
/ /

여러 문서 찾기

collection.find()로 컬렉션에 있는 여러 문서를 쿼리할 수 있습니다. find() 메서드는 사용자가 제공한 쿼리 문서를 사용하여 컬렉션에서 쿼리와 일치하는 문서의 하위 집합을 일치시킵니다. 쿼리 문서를 제공하지 않는 경우(또는 빈 문서를 제공하는 경우) MongoDB는 컬렉션의 모든 문서를 반환합니다. MongoDB 쿼리에 대한 자세한 내용은 쿼리 문서에 대한 문서를 참조하세요.

정렬프로젝션 과 같은 추가 쿼리 옵션을 정의하여 결과 세트를 구성할 수도 있습니다. sortprojection 객체의 find() 메서드 호출의 옵션 매개변수에서 이를 지정할 수 있습니다. collection.find()을 참조하세요. 메서드에 전달할 수 있는 매개변수에 대한 자세한 내용은 를 참조하세요.

find() 메서드는 쿼리 결과를 관리하는 FindCursor를 반환합니다. for await...of 구문 또는 다음 커서 메서드를 사용하여 일치하는 문서를 반복할 수 있습니다:

  • next()

  • toArray()

쿼리와 일치하는 문서가 없는 경우 find() 은 빈 커서를 반환합니다.

find() 메서드를 사용하여 다음 환경에서 호스팅되는 배포서버에 Node.js 드라이버를 연결하고 사용할 수 있습니다.

  • MongoDB Atlas: 클라우드에서의 MongoDB 배포를 위한 완전 관리형 서비스

  • MongoDB Enterprise: 구독 기반의 자체 관리형 MongoDB 버전입니다.

  • MongoDB Community: 소스 사용 가능하고, 무료로 사용할 수 있는 자체 관리형 MongoDB 버전

MongoDB Atlas에서 호스팅되는 배포를 위해 Atlas UI에서 문서를 찾는 방법에 대한 자세한 내용은 문서 생성, 보기, 업데이트 및 삭제를 참조하세요.

다음 스니펫은 movies collection에서 문서를 찾습니다. 다음 매개 변수를 사용합니다:

  • 런타임이 15분 미만인 동영상만 반환하도록 쿼리를 구성하는 쿼리 문서 입니다.

  • 반환된 문서를 제목별로 오름차순(알파벳순으로 'A'가 'Z' 앞에 오고 '1'이 '9' 앞에 오는 방식)으로 정리하는 정렬입니다.

  • 반환된 문서에서 _id 필드를 명시적으로 제외하고 titleimdb 객체 (및 포함된 필드)만 명시적으로 포함하는 프로젝션입니다.

참고

이 예시를 사용하여 MongoDB 인스턴스에 연결하고 샘플 데이터가 포함된 데이터베이스와 상호 작용할 수 있습니다. MongoDB 인스턴스에 연결하고 샘플 데이터 세트를 로드하는 방법에 대해 자세히 알아보려면 사용 예제 가이드를 참조하세요.

1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10
11 // Get the database and collection on which to run the operation
12 const database = client.db("sample_mflix");
13 const movies = database.collection("movies");
14
15 // Query for movies that have a runtime less than 15 minutes
16 const query = { runtime: { $lt: 15 } };
17
18 const options = {
19 // Sort returned documents in ascending order by title (A->Z)
20 sort: { title: 1 },
21 // Include only the `title` and `imdb` fields in each returned document
22 projection: { _id: 0, title: 1, imdb: 1 },
23 };
24
25 // Execute query
26 const cursor = movies.find(query, options);
27
28 // Print a message if no documents were found
29 if ((await movies.countDocuments(query)) === 0) {
30 console.log("No documents found!");
31 }
32
33 // Print returned documents
34 for await (const doc of cursor) {
35 console.dir(doc);
36 }
37
38 } finally {
39 await client.close();
40 }
41}
42run().catch(console.dir);
1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8type Minutes = number;
9
10interface IMDB {
11 rating: number;
12 votes: number;
13 id: number;
14}
15
16interface Movie {
17 title: string;
18 imdb: IMDB;
19 runtime: Minutes;
20}
21
22async function run() {
23 try {
24 const database = client.db("sample_mflix");
25 const movies = database.collection<Movie>("movies");
26
27 const query = { runtime: { $lt: 15 } };
28 const cursor = movies.find<Movie>(
29 query,
30 {
31 sort: { title: 1 },
32 projection: { _id: 0, title: 1, imdb: 1 },
33 }
34 );
35
36 if ((await movies.countDocuments(query)) === 0) {
37 console.warn("No documents found!");
38 }
39
40 for await (const doc of cursor) {
41 console.dir(doc);
42 }
43 } finally {
44 await client.close();
45 }
46}
47run().catch(console.dir);

앞의 예시를 실행하면 다음과 같은 출력이 표시됩니다.

{ 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 } }
...

sortprojection 옵션은 find() 메서드에 연결된 메서드(각각 sort()project())로 지정할 수도 있습니다. 다음 두 명령은 동일합니다:

movies.find({ runtime: { $lt: 15 } }, { sort: { title: 1 }, projection: { _id: 0, title: 1, imdb: 1 }});
movies.find({ runtime: { $lt: 15 } }).sort({ title: 1}).project({ _id: 0, title: 1, imdb: 1 });

돌아가기

문서 찾기