Docs Menu
Docs Home
/ /

반환된 결과 건너뛰기

이 가이드 에서는 MongoDB Rust 드라이버 를 사용하여 결과를 반환할 때 지정된 수의 문서를 건너뛰는 읽기 작업을 수행하는 방법을 학습 수 있습니다.

이 가이드의 예시에서는 다음 Book 구조체를 books collection의 문서 모델로 사용합니다.

#[derive(Debug, Serialize, Deserialize)]
struct Book {
name: String,
author: String,
length: i32,
}

다음 코드는 books 컬렉션 에 샘플 데이터를 삽입하는 방법을 보여줍니다.

let uri = "connection string";
let client = Client::with_uri_str(uri).await?;
let my_coll: Collection<Book> = client.database("db").collection("books");
let books = vec![
Book {
name: "The Brothers Karamazov".to_string(),
author: "Dostoyevsky".to_string(),
length: 824,
},
Book {
name: "Atlas Shrugged".to_string(),
author: "Rand".to_string(),
length: 1088,
},
Book {
name: "Les Misérables".to_string(),
author: "Hugo".to_string(),
length: 1462,
},
Book {
name: "A Dance with Dragons".to_string(),
author: "Martin".to_string(),
length: 1104,
},
];
my_coll.insert_many(books, None).await?;

쿼리 로 검색된 결과를 건너뛰거나 집계 파이프라인 내의 결과를 건너뛸 수 있습니다.

건너뛴 문서의 수가 쿼리 와 일치하는 문서 수를 초과하는 경우 해당 쿼리 는 문서를 반환하지 않습니다.

찾기 작업은 어떤 필드에서도 정렬되지 않은 기본 순서 로 문서를 반환합니다. 임의의 문서를 건너뛰는 것을 방지하려면 건너뛰기 옵션을 설정하기 전에 sort() 메서드를 사용하여 고유 값이 있는 필드 에서 문서를 정렬합니다. 학습 보려면 결과 정렬 가이드 를 참조하세요.

문서를 건너뛰려면 FindOptions 인스턴스 초기화하고 skip() 메서드를 사용하여 건너뛸 문서 수를 지정하면 됩니다. 그런 다음 FindOptions 구조체를 find() 메서드에 매개변수로 전달합니다.

이 예시 에서는 다음 조치를 수행하는 find() 작업을 실행합니다.

  • 결과를 author 필드 값의 오름차순으로 정렬합니다.

  • 처음 두 문서를 건너뜁니다.

  • 나머지 문서를 반환합니다.

let find_options = FindOptions::builder()
.sort(doc! { "author": 1 })
.skip(2)
.build();
let mut cursor = my_coll.find(doc! {}, find_options).await?;
while let Some(result) = cursor.try_next().await? {
println!("{:?}", result);
}
Book { name: "A Dance with Dragons", author: "Martin", length: 1104 }
Book { name: "Atlas Shrugged", author: "Rand", length: 1088 }

집계 파이프라인 의 $skip 단계를 사용하여 문서를 건너뛸 수 있습니다. 집계 작업에 학습 보려면 애그리게이션 가이드 를 참조하세요.

이 예시 에서는 다음 작업을 수행하는 집계 파이프라인 을 실행합니다.

  • 결과를 author 필드 값의 오름차순으로 정렬합니다.

  • 첫 번째 문서 건너뛰기

  • 나머지 문서를 반환합니다.

let pipeline = vec![
doc! { "$match": {} },
doc! { "$sort": { "author": 1 } },
doc! { "$skip": 1 },
];
let mut cursor = my_coll.aggregate(pipeline, None).await?;
while let Some(result) = cursor.try_next().await? {
println!("{:?}", result);
}
Document({"_id": ObjectId("..."), "name": String("Les Misérables"), "author": String("Hugo"), "length": Int32(1462)})
Document({"_id": ObjectId("..."), "name": String("A Dance with Dragons"), "author": String("Martin"), "length": Int32(1104)})
Document({"_id": ObjectId("..."), "name": String("Atlas Shrugged"), "author": String("Rand"), "length": Int32(1088)})

이 가이드 에 언급된 작업에 학습 보려면 다음 가이드를 참조하세요.

이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.

  • find()

  • 찾기 옵션

  • FindOneOptions

  • 커서

  • 집계()

  • AggregateOptions

돌아가기

결과 정렬

이 페이지의 내용