Docs Menu
Docs Home
/ / /
Node.js 드라이버

MongoDB 검색 쿼리 실행

In this guide, you can learn how to use the Node.js driver to run MongoDB Search queries on a collection. MongoDB Search enables you to perform full-text searches on collections hosted on MongoDB Atlas. MongoDB Search indexes specify the behavior of the search and which fields to index.

이 가이드의 예시에서는 Atlas 샘플 데이터 세트sample_mflix 데이터베이스에 있는 movies 컬렉션을 사용합니다. 무료 MongoDB Atlas 클러스터를 생성하고 샘플 데이터 세트를 로드하는 방법을 알아보려면 Atlas 시작하기 가이드를 참조하세요.

This section shows how to create an aggregation pipeline to run a MongoDB Search query on a collection. In your array of pipeline stages, add the $search stage to specify the search criteria. Then, call the aggregate() method and pass your pipeline array as a parameter.

집계 작업에 대해 자세히 알아보려면 집계 작업 가이드를 참조하세요.

Before running a MongoDB Search query, you must create a MongoDB Search index on your collection. To learn how to programmatically create a MongoDB Search index, see the MongoDB Search and MongoDB Vector Search Indexes section of the Indexes guide.

This example runs a MongoDB Search query by performing the following actions:

  • title 필드 에 "Alabama"라는 단어가 포함된 문서를 쿼리 하도록 운전자 에 지시하는 $search 단계를 생성합니다.

  • 드라이버가 쿼리 결과에 title 필드를 포함하도록 지시하는 $project 단계를 만듭니다.

  • 파이프라인 단계를 aggregate() 메서드에 전달하고 결과를 출력합니다.

const pipeline = [
{
$search: {
index: "default", // Replace with your search index name
text: {
query: "Alabama",
path: "title"
}
}
},
{
$project: {
title: 1
}
}
];
const cursor = collection.aggregate(pipeline);
for await (const document of cursor) {
console.log(document);
}
{
_id: new ObjectId('...'),
title: 'Alabama Moon'
}
{
_id: new ObjectId('...'),
title: 'Crazy in Alabama'
}
{
_id: new ObjectId('...'),
title: 'Sweet Home Alabama'
}

Node.js Driver MongoDB Search Examples

To view more examples that use the Node.js driver to perform Atlas Search queries, see MongoDB Search Tutorials in the Atlas documentation.

To learn more about MongoDB Search, see MongoDB Search in the Atlas documentation.

메서드에 대해 aggregate() 자세히 학습 API 설명서를 참조하세요.

돌아가기

데이터베이스 명령 실행

이 페이지의 내용