Docs Menu
Docs Home
/
데이터베이스 매뉴얼
/ / /

데이터 필터링

이 튜토리얼에서는 집계 파이프라인 구성하고, 컬렉션 에서 집계 수행하고, 선택한 언어 사용하여 결과를 표시하는 방법을 보여 줍니다.

이 튜토리얼에서는 컬렉션 에 있는 문서의 특정 하위 집합을 쿼리 방법을 보여 줍니다.

집계 파이프라인 다음 작업을 수행합니다.

  • 문서의 하위 집합을 필드 값으로 일치

  • 결과 문서 서식 지정


➤ 오른쪽 상단의 언어 선택 드롭다운 메뉴를 사용하여 다음 예제의 언어 설정하다 하거나 MongoDB Shell 선택합니다.


이 예시 각 사람의 이름, 생년월일, 직업 및 기타 세부 정보를 설명하는 문서가 포함된 persons 컬렉션 사용합니다. 집계 필드 값이 지정된 기준과 일치하는지 여부에 따라 문서를 선택합니다.

persons 컬렉션 만들려면 insertMany() 메서드를 사용합니다.

db.persons.deleteMany({})
db.persons.insertMany( [
{
person_id: "6392529400",
firstname: "Elise",
lastname: "Smith",
dateofbirth: new Date("1972-01-13T09:32:07Z"),
vocation: "ENGINEER",
address: {
number: 5625,
street: "Tipa Circle",
city: "Wojzinmoj",
}
},
{
person_id: "1723338115",
firstname: "Olive",
lastname: "Ranieri",
dateofbirth: new Date("1985-05-12T23:14:30Z"),
gender: "FEMALE",
vocation: "ENGINEER",
address: {
number: 9303,
street: "Mele Circle",
city: "Tobihbo",
}
},
{
person_id: "8732762874",
firstname: "Toni",
lastname: "Jones",
dateofbirth: new Date("1991-11-23T16:53:56Z"),
vocation: "POLITICIAN",
address: {
number: 1,
street: "High Street",
city: "Upper Abbeywoodington",
}
},
{
person_id: "7363629563",
firstname: "Bert",
lastname: "Gooding",
dateofbirth: new Date("1941-04-07T22:11:52Z"),
vocation: "FLORIST",
address: {
number: 13,
street: "Upper Bold Road",
city: "Redringtonville",
}
},
{
person_id: "1029648329",
firstname: "Sophie",
lastname: "Celements",
dateofbirth: new Date("1959-07-06T17:35:45Z"),
vocation: "ENGINEER",
address: {
number: 5,
street: "Innings Close",
city: "Basilbridge",
}
},
{
person_id: "7363626383",
firstname: "Carl",
lastname: "Simmons",
dateofbirth: new Date("1998-12-26T13:13:55Z"),
vocation: "ENGINEER",
address: {
number: 187,
street: "Hillside Road",
city: "Kenningford",
}
}
] )

이 집계 튜토리얼을 시작하기 전에 새 C 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

운전자 설치하고 MongoDB 에 연결하는 방법을 학습 C 드라이버 시작하기 가이드참조하세요.

C 드라이버 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습 애그리게이션 가이드참조하세요.

운전자 설치한 후 agg-tutorial.c라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

#include <stdio.h>
#include <bson/bson.h>
#include <mongoc/mongoc.h>
int main(void)
{
mongoc_init();
// Replace the placeholder with your connection string.
char *uri = "<connection string>";
mongoc_client_t* client = mongoc_client_new(uri);
// Get a reference to relevant collections.
// ... mongoc_collection_t *some_coll = mongoc_client_get_collection(client, "agg_tutorials_db", "some_coll");
// ... mongoc_collection_t *another_coll = mongoc_client_get_collection(client, "agg_tutorials_db", "another_coll");
// Delete any existing documents in collections if needed.
// ... {
// ... bson_t *filter = bson_new();
// ... bson_error_t error;
// ... if (!mongoc_collection_delete_many(some_coll, filter, NULL, NULL, &error))
// ... {
// ... fprintf(stderr, "Delete error: %s\n", error.message);
// ... }
// ... bson_destroy(filter);
// ... }
// Insert sample data into the collection or collections.
// ... {
// ... size_t num_docs = ...;
// ... bson_t *docs[num_docs];
// ...
// ... docs[0] = ...;
// ...
// ... bson_error_t error;
// ... if (!mongoc_collection_insert_many(some_coll, (const bson_t **)docs, num_docs, NULL, NULL, &error))
// ... {
// ... fprintf(stderr, "Insert error: %s\n", error.message);
// ... }
// ...
// ... for (int i = 0; i < num_docs; i++)
// ... {
// ... bson_destroy(docs[i]);
// ... }
// ... }
{
const bson_t *doc;
// Add code to create pipeline stages.
bson_t *pipeline = BCON_NEW("pipeline", "[",
// ... Add pipeline stages here.
"]");
// Run the aggregation.
// ... mongoc_cursor_t *results = mongoc_collection_aggregate(some_coll, MONGOC_QUERY_NONE, pipeline, NULL, NULL);
bson_destroy(pipeline);
// Print the aggregation results.
while (mongoc_cursor_next(results, &doc))
{
char *str = bson_as_canonical_extended_json(doc, NULL);
printf("%s\n", str);
bson_free(str);
}
bson_error_t error;
if (mongoc_cursor_error(results, &error))
{
fprintf(stderr, "Aggregation error: %s\n", error.message);
}
mongoc_cursor_destroy(results);
}
// Clean up resources.
// ... mongoc_collection_destroy(some_coll);
mongoc_client_destroy(client);
mongoc_cleanup();
return EXIT_SUCCESS;
}

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포의 연결 문자열 찾는 방법을 학습하려면 C 시작하기 가이드의 연결 문자열 만들기 단계를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

char *uri = "mongodb+srv://mongodb-example:27017";

이 예시 각 사람의 이름, 생년월일, 직업 및 기타 세부 정보를 설명하는 문서가 포함된 persons 컬렉션 사용합니다. 집계 필드 값이 지정된 기준과 일치하는지 여부에 따라 문서를 선택합니다.

persons 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

mongoc_collection_t *persons = mongoc_client_get_collection(client, "agg_tutorials_db", "persons");
{
bson_t *filter = bson_new();
bson_error_t error;
if (!mongoc_collection_delete_many(persons, filter, NULL, NULL, &error))
{
fprintf(stderr, "Delete error: %s\n", error.message);
}
bson_destroy(filter);
}
{
size_t num_docs = 6;
bson_t *docs[num_docs];
docs[0] = BCON_NEW(
"person_id", "6392529400",
"firstname", "Elise",
"lastname", "Smith",
"dateofbirth", BCON_DATE_TIME(653616727000UL), // 1972-01-13T09:32:07Z
"vocation", "ENGINEER",
"address", "{",
"number", BCON_INT32(5625),
"street", "Tipa Circle",
"city", "Wojzinmoj",
"}");
docs[1] = BCON_NEW(
"person_id", "1723338115",
"firstname", "Olive",
"lastname", "Ranieri",
"dateofbirth", BCON_DATE_TIME(485113500000UL), // 1985-05-12T23:14:30Z
"gender", "FEMALE",
"vocation", "ENGINEER",
"address", "{",
"number", BCON_INT32(9303),
"street", "Mele Circle",
"city", "Tobihbo",
"}");
docs[2] = BCON_NEW(
"person_id", "8732762874",
"firstname", "Toni",
"lastname", "Jones",
"dateofbirth", BCON_DATE_TIME(690559710000UL), // 1991-11-23T16:53:56Z
"vocation", "POLITICIAN",
"address", "{",
"number", BCON_INT32(1),
"street", "High Street",
"city", "Upper Abbeywoodington",
"}");
docs[3] = BCON_NEW(
"person_id", "7363629563",
"firstname", "Bert",
"lastname", "Gooding",
"dateofbirth", BCON_DATE_TIME(449595112000UL), // 1941-04-07T22:11:52Z
"vocation", "FLORIST",
"address", "{",
"number", BCON_INT32(13),
"street", "Upper Bold Road",
"city", "Redringtonville",
"}");
docs[4] = BCON_NEW(
"person_id", "1029648329",
"firstname", "Sophie",
"lastname", "Celements",
"dateofbirth", BCON_DATE_TIME(316265745000UL), // 1959-07-06T17:35:45Z
"vocation", "ENGINEER",
"address", "{",
"number", BCON_INT32(5),
"street", "Innings Close",
"city", "Basilbridge",
"}");
docs[5] = BCON_NEW(
"person_id", "7363626383",
"firstname", "Carl",
"lastname", "Simmons",
"dateofbirth", BCON_DATE_TIME(915250045000UL), // 1998-12-26T13:13:55Z
"vocation", "ENGINEER",
"address", "{",
"number", BCON_INT32(187),
"street", "Hillside Road",
"city", "Kenningford",
"}");
bson_error_t error;
if (!mongoc_collection_insert_many(persons, (const bson_t **)docs, num_docs, NULL, NULL, &error))
{
fprintf(stderr, "Insert error: %s\n", error.message);
}
for (int i = 0; i < num_docs; i++)
{
bson_destroy(docs[i]);
}
}

집계 튜토리얼을 따라 하기 전에 새 C++ 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

운전자 설치하고 MongoDB 에 연결하는 방법을 학습 C++ 시작하기 튜토리얼을 참조하세요.

C++ 운전자 사용에 대해 자세히 학습하려면 API 설명서를 참조하세요.

C++ 드라이버 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습 애그리게이션 가이드참조하세요.

운전자 설치한 후 agg-tutorial.cpp라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

#include <iostream>
#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/builder/basic/kvp.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/pipeline.hpp>
#include <mongocxx/uri.hpp>
#include <chrono>
using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;
using bsoncxx::builder::basic::make_array;
int main() {
mongocxx::instance instance;
// Replace the placeholder with your connection string.
mongocxx::uri uri("<connection string>");
mongocxx::client client(uri);
auto db = client["agg_tutorials_db"];
// Delete existing data in the database, if necessary.
db.drop();
// Get a reference to relevant collections.
// ... auto some_coll = db["..."];
// ... auto another_coll = db["..."];
// Insert sample data into the collection or collections.
// ... some_coll.insert_many(docs);
// Create an empty pipelne.
mongocxx::pipeline pipeline;
// Add code to create pipeline stages.
// pipeline.match(make_document(...));
// Run the aggregation and print the results.
auto cursor = orders.aggregate(pipeline);
for (auto&& doc : cursor) {
std::cout << bsoncxx::to_json(doc, bsoncxx::ExtendedJsonMode::k_relaxed) << std::endl;
}
}

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포의 연결 문자열 찾는 방법을 학습하려면 C++ 시작하기 튜토리얼의 연결 문자열 만들기 단계를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

mongocxx::uri uri{"mongodb+srv://mongodb-example:27017"};

이 예시 각 사람의 이름, 생년월일, 직업 및 기타 세부 정보를 설명하는 문서가 포함된 persons 컬렉션 사용합니다. 집계 필드 값이 지정된 기준과 일치하는지 여부에 따라 문서를 선택합니다.

persons 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

auto persons = db["persons"];
std::vector<bsoncxx::document::value> docs = {
bsoncxx::from_json(R"({
"person_id": "6392529400",
"firstname": "Elise",
"lastname": "Smith",
"dateofbirth": {"$date": 620947927},
"vocation": "ENGINEER",
"address": {
"number": 5625,
"street": "Tipa Circle",
"city": "Wojzinmoj"
}
})"),
bsoncxx::from_json(R"({
"person_id": "1723338115",
"firstname": "Olive",
"lastname": "Ranieri",
"dateofbirth": {"$date": 485529270000},
"gender": "FEMALE",
"vocation": "ENGINEER",
"address": {
"number": 9303,
"street": "Mele Circle",
"city": "Tobihbo"
}
})"),
bsoncxx::from_json(R"({
"person_id": "8732762874",
"firstname": "Toni",
"lastname": "Jones",
"dateofbirth": {"$date": 690978836000},
"vocation": "POLITICIAN",
"address": {
"number": 1,
"street": "High Street",
"city": "Upper Abbeywoodington"
}
})"),
bsoncxx::from_json(R"({
"person_id": "7363629563",
"firstname": "Bert",
"lastname": "Gooding",
"dateofbirth": {"$date": -88368048000},
"vocation": "FLORIST",
"address": {
"number": 13,
"street": "Upper Bold Road",
"city": "Redringtonville"
}
})"),
bsoncxx::from_json(R"({
"person_id": "1029648329",
"firstname": "Sophie",
"lastname": "Celements",
"dateofbirth": {"$date": -31561935000},
"vocation": "ENGINEER",
"address": {
"number": 5,
"street": "Innings Close",
"city": "Basilbridge"
}
})"),
bsoncxx::from_json(R"({
"person_id": "7363626383",
"firstname": "Carl",
"lastname": "Simmons",
"dateofbirth": {"$date": 915148835000},
"vocation": "ENGINEER",
"address": {
"number": 187,
"street": "Hillside Road",
"city": "Kenningford"
}
})")
};
auto result = persons.insert_many(docs); // Might throw an exception

이 집계 튜토리얼을 시작하기 전에 새 C#/ .NET 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

운전자 설치하고 MongoDB 에 연결하는 방법을 학습하려면 C#/ .NET 드라이버 빠른 시작 가이드를 참조하세요.

C#/ .NET 드라이버 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습 애그리게이션 가이드참조하세요.

운전자 설치한 후 다음 코드를 Program.cs 파일 에 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
// Define data model classes.
// ... public class MyClass { ... }
// Replace the placeholder with your connection string.
var uri = "<connection string>";
var client = new MongoClient(uri);
var aggDB = client.GetDatabase("agg_tutorials_db");
// Get a reference to relevant collections.
// ... var someColl = aggDB.GetCollection<MyClass>("someColl");
// ... var anotherColl = aggDB.GetCollection<MyClass>("anotherColl");
// Delete any existing documents in collections if needed.
// ... someColl.DeleteMany(Builders<MyClass>.Filter.Empty);
// Insert sample data into the collection or collections.
// ... someColl.InsertMany(new List<MyClass> { ... });
// Add code to chain pipeline stages to the Aggregate() method.
// ... var results = someColl.Aggregate().Match(...);
// Print the aggregation results.
foreach (var result in results.ToList())
{
Console.WriteLine(result);
}

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포의 연결 문자열 찾는 방법을 학습하려면 C# 빠른 시작 가이드의 Atlas에서 무료 계층 클러스터 설정 단계를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

var uri = "mongodb+srv://mongodb-example:27017";

이 예시 각 사람의 이름, 생년월일, 직업 및 기타 세부 정보를 설명하는 문서가 포함된 persons 컬렉션 사용합니다. 집계 필드 값이 지정된 기준과 일치하는지 여부에 따라 문서를 선택합니다.

먼저 C# 클래스를 만들어 persons 컬렉션 의 데이터를 모델링합니다.

public class Person
{
[BsonId]
public ObjectId Id { get; set; }
public string PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
[BsonIgnoreIfNull]
public string? Gender { get; set; }
public string Vocation { get; set; }
public Address Address { get; set; }
}
public class Address
{
public int Number { get; set; }
public string Street { get; set; }
public string City { get; set; }
}

persons 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

var persons = aggDB.GetCollection<Person>("persons");
persons.DeleteMany(Builders<Person>.Filter.Empty);
persons.InsertMany(new List<Person>
{
new Person
{
PersonId = "6392529400",
FirstName = "Elise",
LastName = "Smith",
DateOfBirth = DateTime.Parse("1972-01-13T09:32:07Z"),
Vocation = "ENGINEER",
Address = new Address
{
Number = 5625,
Street = "Tipa Circle",
City = "Wojzinmoj"
}
},
new Person
{
PersonId = "1723338115",
FirstName = "Olive",
LastName = "Ranieri",
DateOfBirth = DateTime.Parse("1985-05-12T23:14:30Z"),
Gender = "FEMALE",
Vocation = "ENGINEER",
Address = new Address
{
Number = 9303,
Street = "Mele Circle",
City = "Tobihbo"
}
},
new Person
{
PersonId = "8732762874",
FirstName = "Toni",
LastName = "Jones",
DateOfBirth = DateTime.Parse("1991-11-23T16:53:56Z"),
Vocation = "POLITICIAN",
Address = new Address
{
Number = 1,
Street = "High Street",
City = "Upper Abbeywoodington"
}
},
new Person
{
PersonId = "7363629563",
FirstName = "Bert",
LastName = "Gooding",
DateOfBirth = DateTime.Parse("1941-04-07T22:11:52Z"),
Vocation = "FLORIST",
Address = new Address
{
Number = 13,
Street = "Upper Bold Road",
City = "Redringtonville"
}
},
new Person
{
PersonId = "1029648329",
FirstName = "Sophie",
LastName = "Celements",
DateOfBirth = DateTime.Parse("1959-07-06T17:35:45Z"),
Vocation = "ENGINEER",
Address = new Address
{
Number = 5,
Street = "Innings Close",
City = "Basilbridge"
}
},
new Person
{
PersonId = "7363626383",
FirstName = "Carl",
LastName = "Simmons",
DateOfBirth = DateTime.Parse("1998-12-26T13:13:55Z"),
Vocation = "ENGINEER",
Address = new Address
{
Number = 187,
Street = "Hillside Road",
City = "Kenningford"
}
}
});

이 집계 튜토리얼을 시작하기 전에 새 고 (Go) 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

운전자 설치하고 MongoDB 에 연결하는 방법을 학습하려면 고 (Go) 드라이버 빠른 시작 가이드를 참조하세요.

고 (Go) 드라이버 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습 애그리게이션 가이드참조하세요.

운전자 설치한 후 agg_tutorial.go라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

package main
import (
"context"
"fmt"
"log"
"time"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
// Define structs.
// type MyStruct struct { ... }
func main() {
// Replace the placeholder with your connection string.
const uri = "<connection string>"
client, err := mongo.Connect(options.Client().ApplyURI(uri))
if err != nil {
log.Fatal(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
log.Fatal(err)
}
}()
aggDB := client.Database("agg_tutorials_db")
// Get a reference to relevant collections.
// ... someColl := aggDB.Collection("...")
// ... anotherColl := aggDB.Collection("...")
// Delete any existing documents in collections if needed.
// ... someColl.DeleteMany(context.TODO(), bson.D{})
// Insert sample data into the collection or collections.
// ... _, err = someColl.InsertMany(...)
// Add code to create pipeline stages.
// ... myStage := bson.D{{...}}
// Create a pipeline that includes the stages.
// ... pipeline := mongo.Pipeline{...}
// Run the aggregation.
// ... cursor, err := someColl.Aggregate(context.TODO(), pipeline)
if err != nil {
log.Fatal(err)
}
defer func() {
if err := cursor.Close(context.TODO()); err != nil {
log.Fatalf("failed to close cursor: %v", err)
}
}()
// Decode the aggregation results.
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
log.Fatalf("failed to decode results: %v", err)
}
// Print the aggregation results.
for _, result := range results {
res, _ := bson.MarshalExtJSON(result, false, false)
fmt.Println(string(res))
}
}

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포서버의 연결 문자열 찾는 방법을 학습하려면 고 (Go) 빠른 시작 가이드의 MongoDB 클러스터 만들기 단계를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

const uri = "mongodb+srv://mongodb-example:27017";

이 예시 각 사람의 이름, 생년월일, 직업 및 기타 세부 정보를 설명하는 문서가 포함된 persons 컬렉션 사용합니다. 집계 필드 값이 지정된 기준과 일치하는지 여부에 따라 문서를 선택합니다.

먼저 고 (Go) 구조체를 만들어 persons 컬렉션 의 데이터를 모델링합니다.

type Person struct {
PersonID string `bson:"person_id"`
Firstname string `bson:"firstname"`
Lastname string `bson:"lastname"`
Gender string `bson:"gender,omitempty"`
DateOfBirth bson.DateTime `bson:"dateofbirth"`
Vocation string `bson:"vocation"`
Address Address `bson:"address"`
}
type Address struct {
Number int
Street string
City string
}

persons 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

persons := aggDB.Collection("persons")
persons.DeleteMany(context.TODO(), bson.D{})
_, err = persons.InsertMany(context.TODO(), []interface{}{
Person{
PersonID: "6392529400",
Firstname: "Elise",
Lastname: "Smith",
DateOfBirth: bson.NewDateTimeFromTime(time.Date(1972, 1, 13, 9, 32, 7, 0, time.UTC)),
Vocation: "ENGINEER",
Address: Address{Number: 5625, Street: "Tipa Circle", City: "Wojzinmoj"},
},
Person{
PersonID: "1723338115",
Firstname: "Olive",
Lastname: "Ranieri",
Gender: "FEMALE",
DateOfBirth: bson.NewDateTimeFromTime(time.Date(1985, 5, 12, 23, 14, 30, 0, time.UTC)),
Vocation: "ENGINEER",
Address: Address{Number: 9303, Street: "Mele Circle", City: "Tobihbo"},
},
Person{
PersonID: "8732762874",
Firstname: "Toni",
Lastname: "Jones",
DateOfBirth: bson.NewDateTimeFromTime(time.Date(1991, 11, 23, 16, 53, 56, 0, time.UTC)),
Vocation: "POLITICIAN",
Address: Address{Number: 1, Street: "High Street", City: "Upper Abbeywoodington"},
},
Person{
PersonID: "7363629563",
Firstname: "Bert",
Lastname: "Gooding",
DateOfBirth: bson.NewDateTimeFromTime(time.Date(1941, 4, 7, 22, 11, 52, 0, time.UTC)),
Vocation: "FLORIST",
Address: Address{Number: 13, Street: "Upper Bold Road", City: "Redringtonville"},
},
Person{
PersonID: "1029648329",
Firstname: "Sophie",
Lastname: "Celements",
DateOfBirth: bson.NewDateTimeFromTime(time.Date(1959, 7, 6, 17, 35, 45, 0, time.UTC)),
Vocation: "ENGINEER",
Address: Address{Number: 5, Street: "Innings Close", City: "Basilbridge"},
},
Person{
PersonID: "7363626383",
Firstname: "Carl",
Lastname: "Simmons",
DateOfBirth: bson.NewDateTimeFromTime(time.Date(1998, 12, 26, 13, 13, 55, 0, time.UTC)),
Vocation: "ENGINEER",
Address: Address{Number: 187, Street: "Hillside Road", City: "Kenningford"},
},
})
if err != nil {
log.Fatal(err)
}

집계 튜토리얼을 시작하기 전에 새 Java 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

운전자 설치하고 MongoDB 에 연결하는 방법을 학습 Java 드라이버 시작하기 가이드참조하세요.

Java Sync 드라이버 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습 애그리게이션 가이드참조하세요.

운전자 설치한 후 AggTutorial.java라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

package org.example;
// Modify imports for each tutorial as needed.
import com.mongodb.client.*;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Sorts;
import org.bson.Document;
import org.bson.conversions.Bson;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AggTutorial {
public static void main( String[] args ) {
// Replace the placeholder with your connection string.
String uri = "<connection string>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase aggDB = mongoClient.getDatabase("agg_tutorials_db");
// Get a reference to relevant collections.
// ... MongoCollection<Document> someColl = ...
// ... MongoCollection<Document> anotherColl = ...
// Delete any existing documents in collections if needed.
// ... someColl.deleteMany(Filters.empty());
// Insert sample data into the collection or collections.
// ... someColl.insertMany(...);
// Create an empty pipeline array.
List<Bson> pipeline = new ArrayList<>();
// Add code to create pipeline stages.
// ... pipeline.add(...);
// Run the aggregation.
// ... AggregateIterable<Document> aggregationResult = someColl.aggregate(pipeline);
// Print the aggregation results.
for (Document document : aggregationResult) {
System.out.println(document.toJson());
}
}
}
}

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포의 연결 문자열 찾는 방법을 학습하려면 Java Sync 빠른 시작 가이드의 연결 문자열 만들기 단계를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

String uri = "mongodb+srv://mongodb-example:27017";

이 예시 각 사람의 이름, 생년월일, 직업 및 기타 세부 정보를 설명하는 문서가 포함된 persons 컬렉션 사용합니다. 집계 필드 값이 지정된 기준과 일치하는지 여부에 따라 문서를 선택합니다.

persons 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

MongoCollection<Document> persons = aggDB.getCollection("persons");
persons.deleteMany(Filters.empty());
persons.insertMany(
Arrays.asList(
new Document("person_id", "6392529400")
.append("firstname", "Elise")
.append("lastname", "Smith")
.append("dateofbirth", LocalDateTime.parse("1972-01-13T09:32:07"))
.append("vocation", "ENGINEER")
.append("address", new Document("number", 5625)
.append("street", "Tipa Circle")
.append("city", "Wojzinmoj")),
new Document("person_id", "1723338115")
.append("firstname", "Olive")
.append("lastname", "Ranieri")
.append("dateofbirth", LocalDateTime.parse("1985-05-12T23:14:30"))
.append("gender", "FEMALE")
.append("vocation", "ENGINEER")
.append("address", new Document("number", 9303)
.append("street", "Mele Circle")
.append("city", "Tobihbo")),
new Document("person_id", "8732762874")
.append("firstname", "Toni")
.append("lastname", "Jones")
.append("dateofbirth", LocalDateTime.parse("1991-11-23T16:53:56"))
.append("vocation", "POLITICIAN")
.append("address", new Document("number", 1)
.append("street", "High Street")
.append("city", "Upper Abbeywoodington")),
new Document("person_id", "7363629563")
.append("firstname", "Bert")
.append("lastname", "Gooding")
.append("dateofbirth", LocalDateTime.parse("1941-04-07T22:11:52"))
.append("vocation", "FLORIST")
.append("address", new Document("number", 13)
.append("street", "Upper Bold Road")
.append("city", "Redringtonville")),
new Document("person_id", "1029648329")
.append("firstname", "Sophie")
.append("lastname", "Celements")
.append("dateofbirth", LocalDateTime.parse("1959-07-06T17:35:45"))
.append("vocation", "ENGINEER")
.append("address", new Document("number", 5)
.append("street", "Innings Close")
.append("city", "Basilbridge")),
new Document("person_id", "7363626383")
.append("firstname", "Carl")
.append("lastname", "Simmons")
.append("dateofbirth", LocalDateTime.parse("1998-12-26T13:13:55"))
.append("vocation", "ENGINEER")
.append("address", new Document("number", 187)
.append("street", "Hillside Road")
.append("city", "Kenningford"))
)
);

집계 튜토리얼을 시작하기 전에 새 코틀린 (Kotlin) 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

운전자 설치하고 MongoDB 에 연결하는 방법을 학습 코틀린 (Kotlin) ) 드라이버 빠른 시작 가이드참조하세요.

코틀린 (Kotlin) ) 드라이버 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습 애그리게이션 가이드참조하세요.

운전자 외에도 build.gradle.kts 파일 에 다음 종속성을 추가하고 프로젝트 다시 로드해야 합니다.

dependencies {
// Implements Kotlin serialization
implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:1.5.1")
// Implements Kotlin date and time handling
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.6.1")
}

운전자 설치한 후 AggTutorial.kt라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

package org.example
// Modify imports for each tutorial as needed.
import com.mongodb.client.model.*
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.toJavaLocalDateTime
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import org.bson.Document
import org.bson.conversions.Bson
// Define data classes.
@Serializable
data class MyClass(
...
)
suspend fun main() {
// Replace the placeholder with your connection string.
val uri = "<connection string>"
MongoClient.create(uri).use { mongoClient ->
val aggDB = mongoClient.getDatabase("agg_tutorials_db")
// Get a reference to relevant collections.
// ... val someColl = ...
// Delete any existing documents in collections if needed.
// ... someColl.deleteMany(empty())
// Insert sample data into the collection or collections.
// ... someColl.insertMany( ... )
// Create an empty pipeline.
val pipeline = mutableListOf<Bson>()
// Add code to create pipeline stages.
// ... pipeline.add(...)
// Run the aggregation.
// ... val aggregationResult = someColl.aggregate<Document>(pipeline)
// Print the aggregation results.
aggregationResult.collect { println(it) }
}
}

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포의 연결 문자열 찾는 방법을 학습하려면 코틀린 (Kotlin) 드라이버 빠른 시작 가이드의 클러스터에 연결 단계를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

val uri = "mongodb+srv://mongodb-example:27017"

이 예시 각 사람의 이름, 생년월일, 직업 및 기타 세부 정보를 설명하는 문서가 포함된 persons 컬렉션 사용합니다. 집계 필드 값이 지정된 기준과 일치하는지 여부에 따라 문서를 선택합니다.

먼저 코틀린 (Kotlin) 데이터 클래스를 만들어 persons 컬렉션 의 데이터를 모델링합니다.

@Serializable
data class Address(
val number: Int,
val street: String,
val city: String
)
@Serializable
data class Person(
val personID: String,
val firstname: String,
val lastname: String,
@Contextual val dateOfBirth: LocalDateTime,
val vocation: String,
val address: Address,
val gender: String? = null
)

persons 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

val persons = aggDB.getCollection<Person>("persons")
persons.deleteMany(Filters.empty())
persons.insertMany(
listOf(
Person(
"6392529400",
"Elise",
"Smith",
LocalDateTime.parse("1972-01-13T09:32:07"),
"ENGINEER",
Address(5625, "Tipa Circle", "Wojzinmoj")
),
Person(
"1723338115",
"Olive",
"Ranieri",
LocalDateTime.parse("1985-05-12T23:14:30"),
"ENGINEER",
Address(9303, "Mele Circle", "Tobihbo"),
"FEMALE"
),
Person(
"8732762874",
"Toni",
"Jones",
LocalDateTime.parse("1991-11-23T16:53:56"),
"POLITICIAN",
Address(1, "High Street", "Upper Abbeywoodington")
),
Person(
"7363629563",
"Bert",
"Gooding",
LocalDateTime.parse("1941-04-07T22:11:52"),
"FLORIST",
Address(13, "Upper Bold Road", "Redringtonville")
),
Person(
"1029648329",
"Sophie",
"Celements",
LocalDateTime.parse("1959-07-06T17:35:45"),
"ENGINEER",
Address(5, "Innings Close", "Basilbridge")
),
Person(
"7363626383",
"Carl",
"Simmons",
LocalDateTime.parse("1998-12-26T13:13:55"),
"ENGINEER",
Address(187, "Hillside Road", "Kenningford")
)
)
)

이 집계 튜토리얼을 따라 시작하기 전에 새 Node.js 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

운전자 설치하고 MongoDB 에 연결하는 방법을 학습하려면 Node.js 드라이버 빠른 시작 가이드를 참조하세요.

Node.js 드라이버 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습 애그리게이션 가이드참조하세요.

운전자 설치한 후 agg_tutorial.js라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

const { MongoClient } = require("mongodb");
// Replace the placeholder with your connection string.
const uri = "<connection string>";
const client = new MongoClient(uri);
async function run() {
try {
const aggDB = client.db("agg_tutorials_db");
// Get a reference to relevant collections.
// ... const someColl =
// ... const anotherColl =
// Delete any existing documents in collections.
// ... await someColl.deleteMany({});
// Insert sample data into the collection or collections.
// ... const someData = [ ... ];
// ... await someColl.insertMany(someData);
// Create an empty pipeline array.
const pipeline = [];
// Add code to create pipeline stages.
// ... pipeline.push({ ... })
// Run the aggregation.
// ... const aggregationResult = ...
// Print the aggregation results.
for await (const document of aggregationResult) {
console.log(document);
}
} finally {
await client.close();
}
}
run().catch(console.dir);

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포의 연결 문자열 찾는 방법을 학습하려면 Node.js 빠른 시작 가이드의 연결 문자열 만들기 단계를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

const uri = "mongodb+srv://mongodb-example:27017";

이 예시 각 사람의 이름, 생년월일, 직업 및 기타 세부 정보를 설명하는 문서가 포함된 persons 컬렉션 사용합니다. 집계 필드 값이 지정된 기준과 일치하는지 여부에 따라 문서를 선택합니다.

persons 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

const persons = aggDB.collection("persons");
await persons.deleteMany({});
await persons.insertMany([
{
person_id: "6392529400",
firstname: "Elise",
lastname: "Smith",
dateofbirth: new Date("1972-01-13T09:32:07Z"),
vocation: "ENGINEER",
address: {
number: 5625,
street: "Tipa Circle",
city: "Wojzinmoj",
},
},
{
person_id: "1723338115",
firstname: "Olive",
lastname: "Ranieri",
dateofbirth: new Date("1985-05-12T23:14:30Z"),
gender: "FEMALE",
vocation: "ENGINEER",
address: {
number: 9303,
street: "Mele Circle",
city: "Tobihbo",
},
},
{
person_id: "8732762874",
firstname: "Toni",
lastname: "Jones",
dateofbirth: new Date("1991-11-23T16:53:56Z"),
vocation: "POLITICIAN",
address: {
number: 1,
street: "High Street",
city: "Upper Abbeywoodington",
},
},
{
person_id: "7363629563",
firstname: "Bert",
lastname: "Gooding",
dateofbirth: new Date("1941-04-07T22:11:52Z"),
vocation: "FLORIST",
address: {
number: 13,
street: "Upper Bold Road",
city: "Redringtonville",
},
},
{
person_id: "1029648329",
firstname: "Sophie",
lastname: "Celements",
dateofbirth: new Date("1959-07-06T17:35:45Z"),
vocation: "ENGINEER",
address: {
number: 5,
street: "Innings Close",
city: "Basilbridge",
},
},
{
person_id: "7363626383",
firstname: "Carl",
lastname: "Simmons",
dateofbirth: new Date("1998-12-26T13:13:55Z"),
vocation: "ENGINEER",
address: {
number: 187,
street: "Hillside Road",
city: "Kenningford",
},
},
]);

이 집계 튜토리얼을 시작하기 전에 새 PHP 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

PHP 라이브러리를 설치하고 MongoDB 에 연결하는 방법을 학습하려면 PHP 라이브러리 시작하기 튜토리얼을 참조하세요.

PHP 라이브러리에서 애그리게이션을 수행하는 방법에 대해 자세히 학습하려면 애그리게이션 가이드를 참조하세요.

라이브러리를 설치한 후 agg_tutorial.php라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

<?php
require 'vendor/autoload.php';
// Modify imports for each tutorial as needed.
use MongoDB\Client;
use MongoDB\BSON\UTCDateTime;
use MongoDB\Builder\Pipeline;
use MongoDB\Builder\Stage;
use MongoDB\Builder\Type\Sort;
use MongoDB\Builder\Query;
use MongoDB\Builder\Expression;
use MongoDB\Builder\Accumulator;
use function MongoDB\object;
// Replace the placeholder with your connection string.
$uri = '<connection string>';
$client = new Client($uri);
// Get a reference to relevant collections.
// ... $someColl = $client->agg_tutorials_db->someColl;
// ... $anotherColl = $client->agg_tutorials_db->anotherColl;
// Delete any existing documents in collections if needed.
// ... $someColl->deleteMany([]);
// Insert sample data into the collection or collections.
// ... $someColl->insertMany(...);
// Add code to create pipeline stages within the Pipeline instance.
// ... $pipeline = new Pipeline(...);
// Run the aggregation.
// ... $cursor = $someColl->aggregate($pipeline);
// Print the aggregation results.
foreach ($cursor as $doc) {
echo json_encode($doc, JSON_PRETTY_PRINT), PHP_EOL;
}

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포의 연결 문자열 찾는 방법을 학습 PHP 라이브러리 시작하기 튜토리얼의 연결 문자열 만들기 단계 를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

$uri = 'mongodb+srv://mongodb-example:27017';

이 예시 각 사람의 이름, 생년월일, 직업 및 기타 세부 정보를 설명하는 문서가 포함된 persons 컬렉션 사용합니다. 집계 필드 값이 지정된 기준과 일치하는지 여부에 따라 문서를 선택합니다.

persons 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

$persons = $client->agg_tutorials_db->persons;
$persons->deleteMany([]);
$persons->insertMany(
[
[
'person_id' => '6392529400',
'firstname' => 'Elise',
'lastname' => 'Smith',
'dateofbirth' => new UTCDateTime(new DateTimeImmutable('1972-01-13T09:32:07')),
'vocation' => 'ENGINEER',
'address' => ['number' => 5625, 'Street' => 'Tipa Circle', 'city' => 'Wojzinmoj'],
],
[
'person_id' => '1723338115',
'firstname' => 'Olive',
'lastname' => 'Ranieri',
'gender' => 'FEMALE',
'dateofbirth' => new UTCDateTime(new DateTimeImmutable('1985-05-12T23:14:30')),
'vocation' => 'ENGINEER',
'address' => ['number' => 9303, 'street' => 'Mele Circle', 'city' => 'Tobihbo'],
],
[
'person_id' => '8732762874',
'firstname' => 'Toni',
'lastname' => 'Jones',
'dateofbirth' => new UTCDateTime(new DateTimeImmutable('1991-11-23T16:53:56')),
'vocation' => 'POLITICIAN',
'address' => ['number' => 1, 'street' => 'High Street', 'city' => 'Upper Abbeywoodington'],
],
[
'person_id' => '7363629563',
'firstname' => 'Bert',
'lastname' => 'Gooding',
'dateofbirth' => new UTCDateTime(new DateTimeImmutable('1941-04-07T22:11:52')),
'vocation' => 'FLORIST',
'address' => ['number' => 13, 'street' => 'Upper Bold Road', 'city' => 'Redringtonville'],
],
[
'person_id' => '1029648329',
'firstname' => 'Sophie',
'lastname' => 'Celements',
'dateofbirth' => new UTCDateTime(new DateTimeImmutable('1959-07-06T17:35:45')),
'vocation' => 'ENGINEER',
'address' => ['number' => 5, 'street' => 'Innings Close', 'city' => 'Basilbridge'],
],
[
'person_id' => '7363626383',
'firstname' => 'Carl',
'lastname' => 'Simmons',
'dateofbirth' => new UTCDateTime(new DateTimeImmutable('1998-12-26T13:13:55')),
'vocation' => 'ENGINEER',
'address' => ['number' => 187, 'street' => 'Hillside Road', 'city' => 'Kenningford'],
]
]
);

이 집계 튜토리얼을 따라 시작하기 전에 새 Python 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

PyMongo 설치하고 MongoDB 에 연결하는 방법을 학습 PyMongo 시작하기 튜토리얼을 참조하세요.

PyMongo 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습하려면 애그리게이션 가이드를 참조하세요.

라이브러리를 설치한 후 agg_tutorial.py라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

# Modify imports for each tutorial as needed.
from pymongo import MongoClient
# Replace the placeholder with your connection string.
uri = "<connection string>"
client = MongoClient(uri)
try:
agg_db = client["agg_tutorials_db"]
# Get a reference to relevant collections.
# ... some_coll = agg_db["some_coll"]
# ... another_coll = agg_db["another_coll"]
# Delete any existing documents in collections if needed.
# ... some_coll.delete_many({})
# Insert sample data into the collection or collections.
# ... some_coll.insert_many(...)
# Create an empty pipeline array.
pipeline = []
# Add code to create pipeline stages.
# ... pipeline.append({...})
# Run the aggregation.
# ... aggregation_result = ...
# Print the aggregation results.
for document in aggregation_result:
print(document)
finally:
client.close()

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포의 연결 문자열 찾는 방법을 학습 PHP 라이브러리 시작하기 튜토리얼의 연결 문자열 만들기 단계 를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

uri = "mongodb+srv://mongodb-example:27017"

이 예시 각 사람의 이름, 생년월일, 직업 및 기타 세부 정보를 설명하는 문서가 포함된 persons 컬렉션 사용합니다. 집계 필드 값이 지정된 기준과 일치하는지 여부에 따라 문서를 선택합니다.

persons 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

person_coll = agg_db["persons"]
person_coll.delete_many({})
person_data = [
{
"person_id": "6392529400",
"firstname": "Elise",
"lastname": "Smith",
"dateofbirth": datetime(1972, 1, 13, 9, 32, 7),
"vocation": "ENGINEER",
"address": {
"number": 5625,
"street": "Tipa Circle",
"city": "Wojzinmoj",
},
},
{
"person_id": "1723338115",
"firstname": "Olive",
"lastname": "Ranieri",
"dateofbirth": datetime(1985, 5, 12, 23, 14, 30),
"gender": "FEMALE",
"vocation": "ENGINEER",
"address": {
"number": 9303,
"street": "Mele Circle",
"city": "Tobihbo",
},
},
{
"person_id": "8732762874",
"firstname": "Toni",
"lastname": "Jones",
"dateofbirth": datetime(1991, 11, 23, 16, 53, 56),
"vocation": "POLITICIAN",
"address": {
"number": 1,
"street": "High Street",
"city": "Upper Abbeywoodington",
},
},
{
"person_id": "7363629563",
"firstname": "Bert",
"lastname": "Gooding",
"dateofbirth": datetime(1941, 4, 7, 22, 11, 52),
"vocation": "FLORIST",
"address": {
"number": 13,
"street": "Upper Bold Road",
"city": "Redringtonville",
},
},
{
"person_id": "1029648329",
"firstname": "Sophie",
"lastname": "Celements",
"dateofbirth": datetime(1959, 7, 6, 17, 35, 45),
"vocation": "ENGINEER",
"address": {
"number": 5,
"street": "Innings Close",
"city": "Basilbridge",
},
},
{
"person_id": "7363626383",
"firstname": "Carl",
"lastname": "Simmons",
"dateofbirth": datetime(1998, 12, 26, 13, 13, 55),
"vocation": "ENGINEER",
"address": {
"number": 187,
"street": "Hillside Road",
"city": "Kenningford",
},
},
]
person_coll.insert_many(person_data)

이 집계 튜토리얼을 시작하기 전에 새 Ruby 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

Ruby 드라이버 설치하고 MongoDB 에 연결하는 방법을 학습하려면 Ruby 드라이버 시작하기 가이드를 참조하세요.

Ruby 드라이버 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습하려면 애그리게이션 가이드를 참조하세요.

운전자 설치한 후 agg_tutorial.rb라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

# typed: strict
require 'mongo'
require 'bson'
# Replace the placeholder with your connection string.
uri = "<connection string>"
Mongo::Client.new(uri) do |client|
agg_db = client.use('agg_tutorials_db')
# Get a reference to relevant collections.
# ... some_coll = agg_db[:some_coll]
# Delete any existing documents in collections if needed.
# ... some_coll.delete_many({})
# Insert sample data into the collection or collections.
# ... some_coll.insert_many( ... )
# Add code to create pipeline stages within the array.
# ... pipeline = [ ... ]
# Run the aggregation.
# ... aggregation_result = some_coll.aggregate(pipeline)
# Print the aggregation results.
aggregation_result.each do |doc|
puts doc
end
end

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포의 연결 문자열 찾는 방법을 학습하려면 Ruby 시작하기 가이드의 연결 문자열 만들기 단계를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

uri = "mongodb+srv://mongodb-example:27017"

이 예시 각 사람의 이름, 생년월일, 직업 및 기타 세부 정보를 설명하는 문서가 포함된 persons 컬렉션 사용합니다. 집계 필드 값이 지정된 기준과 일치하는지 여부에 따라 문서를 선택합니다.

persons 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

persons = agg_db[:persons]
persons.delete_many({})
persons.insert_many(
[
{
person_id: "6392529400",
firstname: "Elise",
lastname: "Smith",
dateofbirth: DateTime.parse("1972-01-13T09:32:07Z"),
vocation: "ENGINEER",
address: {
number: 5625,
street: "Tipa Circle",
city: "Wojzinmoj",
},
},
{
person_id: "1723338115",
firstname: "Olive",
lastname: "Ranieri",
dateofbirth: DateTime.parse("1985-05-12T23:14:30Z"),
gender: "FEMALE",
vocation: "ENGINEER",
address: {
number: 9303,
street: "Mele Circle",
city: "Tobihbo",
},
},
{
person_id: "8732762874",
firstname: "Toni",
lastname: "Jones",
dateofbirth: DateTime.parse("1991-11-23T16:53:56Z"),
vocation: "POLITICIAN",
address: {
number: 1,
street: "High Street",
city: "Upper Abbeywoodington",
},
},
{
person_id: "7363629563",
firstname: "Bert",
lastname: "Gooding",
dateofbirth: DateTime.parse("1941-04-07T22:11:52Z"),
vocation: "FLORIST",
address: {
number: 13,
street: "Upper Bold Road",
city: "Redringtonville",
},
},
{
person_id: "1029648329",
firstname: "Sophie",
lastname: "Celements",
dateofbirth: DateTime.parse("1959-07-06T17:35:45Z"),
vocation: "ENGINEER",
address: {
number: 5,
street: "Innings Close",
city: "Basilbridge",
},
},
{
person_id: "7363626383",
firstname: "Carl",
lastname: "Simmons",
dateofbirth: DateTime.parse("1998-12-26T13:13:55Z"),
vocation: "ENGINEER",
address: {
number: 187,
street: "Hillside Road",
city: "Kenningford",
},
},
]
)

이 집계 튜토리얼을 시작하기 전에 새 Rust 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

운전자 설치하고 MongoDB 에 연결하는 방법을 학습 Rust 드라이버 빠른 시작 가이드참조하세요.

Rust 드라이버 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습 애그리게이션 가이드참조하세요.

운전자 설치한 후 agg-tutorial.rs라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

use mongodb::{
bson::{doc, Document},
options::ClientOptions,
Client,
};
use futures::stream::TryStreamExt;
use std::error::Error;
// Define structs.
// #[derive(Debug, Serialize, Deserialize)]
// struct MyStruct { ... }
#[tokio::main]
async fn main() mongodb::error::Result<()> {
// Replace the placeholder with your connection string.
let uri = "<connection string>";
let client = Client::with_uri_str(uri).await?;
let agg_db = client.database("agg_tutorials_db");
// Get a reference to relevant collections.
// ... let some_coll: Collection<T> = agg_db.collection("...");
// ... let another_coll: Collection<T> = agg_db.collection("...");
// Delete any existing documents in collections if needed.
// ... some_coll.delete_many(doc! {}).await?;
// Insert sample data into the collection or collections.
// ... some_coll.insert_many(vec![...]).await?;
// Create an empty pipeline.
let mut pipeline = Vec::new();
// Add code to create pipeline stages.
// pipeline.push(doc! { ... });
// Run the aggregation and print the results.
let mut results = some_coll.aggregate(pipeline).await?;
while let Some(result) = results.try_next().await? {
println!("{:?}\n", result);
}
Ok(())
}

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포서버의 연결 문자열 찾는 방법을 학습하려면 Rust 빠른 시작 가이드의 연결 문자열 만들기 단계를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

let uri = "mongodb+srv://mongodb-example:27017";

이 예시 각 사람의 이름, 생년월일, 직업 및 기타 세부 정보를 설명하는 문서가 포함된 persons 컬렉션 사용합니다. 집계 필드 값이 지정된 기준과 일치하는지 여부에 따라 문서를 선택합니다.

먼저 Rust 구조체를 만들어 persons 컬렉션 의 데이터를 모델링합니다.

#[derive(Debug, Serialize, Deserialize)]
struct Address {
number: i32,
street: String,
city: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct Person {
person_id: String,
firstname: String,
lastname: String,
dateofbirth: DateTime,
vocation: String,
address: Address,
}

persons 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

let persons: Collection<Person> = agg_db.collection("persons");
persons.delete_many(doc! {}).await?;
let data = vec![
Person {
person_id: "6392529400".to_string(),
firstname: "Elise".to_string(),
lastname: "Smith".to_string(),
dateofbirth: DateTime::builder().year(1972).month(1).day(13).hour(9).minute(32).second(7).build().unwrap(),
vocation: "ENGINEER".to_string(),
address: Address {
number: 5625,
street: "Tipa Circle".to_string(),
city: "Wojzinmoj".to_string(),
},
},
Person {
person_id: "1723338115".to_string(),
firstname: "Olive".to_string(),
lastname: "Ranieri".to_string(),
gender: "FEMALE".to_string(),
dateofbirth: DateTime::builder().year(1985).month(5).day(12).hour(23).minute(14).second(30).build().unwrap(),
vocation: "ENGINEER".to_string(),
address: Address {
number: 9303,
street: "Mele Circle".to_string(),
city: "Tobihbo".to_string(),
},
},
Person {
person_id: "8732762874".to_string(),
firstname: "Toni".to_string(),
lastname: "Jones".to_string(),
dateofbirth: DateTime::builder().year(1991).month(11).day(23).hour(16).minute(53).second(56).build().unwrap(),
vocation: "POLITICIAN".to_string(),
address: Address {
number: 1,
street: "High Street".to_string(),
city: "Upper Abbeywoodington".to_string(),
},
},
Person {
person_id: "7363629563".to_string(),
firstname: "Bert".to_string(),
lastname: "Gooding".to_string(),
dateofbirth: DateTime::builder().year(1941).month(4).day(7).hour(22).minute(11).second(52).build().unwrap(),
vocation: "FLORIST".to_string(),
address: Address {
number: 13,
street: "Upper Bold Road".to_string(),
city: "Redringtonville".to_string(),
},
},
Person {
person_id: "1029648329".to_string(),
firstname: "Sophie".to_string(),
lastname: "Celements".to_string(),
dateofbirth: DateTime::builder().year(1959).month(7).day(6).hour(17).minute(35).second(45).build().unwrap(),
vocation: "ENGINEER".to_string(),
address: Address {
number: 5,
street: "Innings Close".to_string(),
city: "Basilbridge".to_string(),
},
},
Person {
person_id: "7363626383".to_string(),
firstname: "Carl".to_string(),
lastname: "Simmons".to_string(),
dateofbirth: DateTime::builder().year(1998).month(12).day(26).hour(13).minute(13).second(55).build().unwrap(),
vocation: "ENGINEER".to_string(),
address: Address {
number: 187,
street: "Hillside Road".to_string(),
city: "Kenningford".to_string(),
},
},
];
persons.insert_many(data).await?;

집계 튜토리얼을 시작하기 전에 새 스칼라 앱 설정하다 해야 합니다. 이 앱 사용하여 MongoDB deployment 에 연결하고, 샘플 데이터를 MongoDB 에 삽입하고, 집계 파이프라인 실행 .

운전자 설치하고 MongoDB 에 연결하는 방법을 학습 스칼라 드라이버 시작하기 가이드 참조하세요.

스칼라 드라이버 에서 애그리게이션을 수행하는 방법에 대해 자세히 학습 애그리게이션 가이드참조하세요.

운전자 설치한 후 AggTutorial.scala라는 파일 만듭니다. 이 파일 에 다음 코드를 붙여넣어 집계 튜토리얼을 위한 앱 템플릿을 만듭니다.

중요

다음 코드에서 코드 주석을 읽고 팔로우 중인 튜토리얼에 대해 수정해야 하는 코드 섹션을 찾습니다.

변경하지 않고 코드를 실행하려고 하면 연결 오류가 발생합니다.

package org.example;
// Modify imports for each tutorial as needed.
import org.mongodb.scala.MongoClient
import org.mongodb.scala.bson.Document
import org.mongodb.scala.model.{Accumulators, Aggregates, Field, Filters, Variable}
import java.text.SimpleDateFormat
object FilteredSubset {
def main(args: Array[String]): Unit = {
// Replace the placeholder with your connection string.
val uri = "<connection string>"
val mongoClient = MongoClient(uri)
Thread.sleep(1000)
val aggDB = mongoClient.getDatabase("agg_tutorials_db")
// Get a reference to relevant collections.
// ... val someColl = aggDB.getCollection("someColl")
// ... val anotherColl = aggDB.getCollection("anotherColl")
// Delete any existing documents in collections if needed.
// ... someColl.deleteMany(Filters.empty()).subscribe(...)
// If needed, create the date format template.
val dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
// Insert sample data into the collection or collections.
// ... someColl.insertMany(...).subscribe(...)
Thread.sleep(1000)
// Add code to create pipeline stages within the Seq.
// ... val pipeline = Seq(...)
// Run the aggregation and print the results.
// ... someColl.aggregate(pipeline).subscribe(...)
Thread.sleep(1000)
mongoClient.close()
}
}

모든 튜토리얼에서는 연결 문자열 자리 표시자를 반드시 배포서버의 연결 문자열로 바꿔야 합니다.

배포의 연결 문자열 찾는 방법을 학습하려면 스칼라 드라이버 시작하기 가이드의 연결 문자열 만들기 단계를 참조하세요.

예를 들어 연결 문자열이 "mongodb+srv://mongodb-example:27017" 인 경우 연결 문자열 할당은 다음과 유사합니다.

val uri = "mongodb+srv://mongodb-example:27017"

이 예시 각 사람의 이름, 생년월일, 직업 및 기타 세부 정보를 설명하는 문서가 포함된 persons 컬렉션 사용합니다. 집계 필드 값이 지정된 기준과 일치하는지 여부에 따라 문서를 선택합니다.

persons 컬렉션 만들고 샘플 데이터를 삽입하려면 애플리케이션 에 다음 코드를 추가합니다.

val persons = aggDB.getCollection("persons")
persons.deleteMany(Filters.empty()).subscribe(
_ => {},
e => println("Error: " + e.getMessage),
)
val dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
persons.insertMany(Seq(
Document(
"person_id" -> "6392529400",
"firstname" -> "Elise",
"lastname" -> "Smith",
"dateofbirth" -> dateFormat.parse("1972-01-13T09:32:07"),
"vocation" -> "ENGINEER",
"address" -> Document(
"number" -> 5625,
"street" -> "Tipa Circle",
"city" -> "Wojzinmoj"
)
),
Document(
"person_id" -> "1723338115",
"firstname" -> "Olive",
"lastname" -> "Ranieri",
"dateofbirth" -> dateFormat.parse("1985-05-12T23:14:30"),
"gender" -> "FEMALE",
"vocation" -> "ENGINEER",
"address" -> Document(
"number" -> 9303,
"street" -> "Mele Circle",
"city" -> "Tobihbo"
)
),
Document(
"person_id" -> "8732762874",
"firstname" -> "Toni",
"lastname" -> "Jones",
"dateofbirth" -> dateFormat.parse("1991-11-23T16:53:56"),
"vocation" -> "POLITICIAN",
"address" -> Document(
"number" -> 1,
"street" -> "High Street",
"city" -> "Upper Abbeywoodington"
)
),
Document(
"person_id" -> "7363629563",
"firstname" -> "Bert",
"lastname" -> "Gooding",
"dateofbirth" -> dateFormat.parse("1941-04-07T22:11:52"),
"vocation" -> "FLORIST",
"address" -> Document(
"number" -> 13,
"street" -> "Upper Bold Road",
"city" -> "Redringtonville"
)
),
Document(
"person_id" -> "1029648329",
"firstname" -> "Sophie",
"lastname" -> "Celements",
"dateofbirth" -> dateFormat.parse("1959-07-06T17:35:45"),
"vocation" -> "ENGINEER",
"address" -> Document(
"number" -> 5,
"street" -> "Innings Close",
"city" -> "Basilbridge"
)
),
Document(
"person_id" -> "7363626383",
"firstname" -> "Carl",
"lastname" -> "Simmons",
"dateofbirth" -> dateFormat.parse("1998-12-26T13:13:55"),
"vocation" -> "ENGINEER",
"address" -> Document(
"number" -> 187,
"street" -> "Hillside Road",
"city" -> "Kenningford"
)
)
)).subscribe(
_ => {},
e => println("Error: " + e.getMessage),
)

다음 단계에서는 집계 파이프라인 만들고 실행 문서의 특정 하위 집합을 필터하다 하는 방법을 보여 줍니다.

1
db.persons.aggregate( [
// Stage 1: Match documents of people who are engineers
{ $match: { "vocation": "ENGINEER" } },
// Stage 2: Sort documents from youngest to oldest
{ $sort: { "dateofbirth": -1 } },
// Stage 3: Limit the results to 3 documents
{ $limit: 3 },
// Stage 4: Remove unneeded fields
{ $unset: [ "_id", "address"] }
] )
2

애그리게이션된 결과에는 세 개의 문서가 포함되어 있습니다. 문서는 ENGINEERvocation 가 있는 가장 어린 세 사람을 가장 어린 사람부터 나이 많은 사람 순으로 나타냅니다. 결과에서는 _idaddress 필드가 생략됩니다.

{
person_id: '7363626383',
firstname: 'Carl',
lastname: 'Simmons',
dateofbirth: ISODate("1998-12-26T13:13:55.000Z"),
vocation: 'ENGINEER'
}
{
person_id: '1723338115',
firstname: 'Olive',
lastname: 'Ranieri',
dateofbirth: ISODate("1985-05-12T23:14:30.000Z"),
gender: 'FEMALE',
vocation: 'ENGINEER'
}
{
person_id: '6392529400',
firstname: 'Elise',
lastname: 'Smith',
dateofbirth: ISODate("1972-01-13T09:32:07.000Z"),
vocation: 'ENGINEER'
}
1

파이프라인 $match 에서 vocation 필드 값이 인 문서를 찾는 단계를 "ENGINEER" 만듭니다.

"{", "$match", "{", "vocation", BCON_UTF8("ENGINEER"), "}", "}",
2

다음으로 필드 기준으로 문서를 $sort 내림차순으로 dateofbirth 정렬하여 가장 어린 사람을 먼저 나열하는 단계를 만듭니다.

"{", "$sort", "{", "dateofbirth", BCON_INT32(-1), "}", "}",
3

다음으로, 파이프라인에 대한 $limit 단계를 생성하여 결과에 처음 3개의 문서만 출력합니다.

"{", "$limit", BCON_INT32(3), "}",
4

마지막으로 $unset 단계를 만듭니다. $unset 단계는 결과 문서에서 불필요한 필드를 제거합니다.

"{", "$unset", "[", BCON_UTF8("_id"), BCON_UTF8("address"), "]", "}",

다른 필드가 있는 문서가 컬렉션에 추가되는 경우 집계 파이프라인이 수정되지 않도록 하려면 $project 대신 $unset 연산자를 사용합니다.

5

persons collection에서 애그리게이션을 수행하려면 애플리케이션 끝에 다음 코드를 추가하세요.

mongoc_cursor_t *results =
mongoc_collection_aggregate(persons, MONGOC_QUERY_NONE, pipeline, NULL, NULL);
bson_destroy(pipeline);

정리 문에 다음 줄을 추가하여 컬렉션 리소스를 정리해야 합니다.

mongoc_collection_destroy(persons);

마지막으로 셸 에서 다음 명령을 실행 실행 파일을 생성하고 실행 .

gcc -o aggc agg-tutorial.c $(pkg-config --libs --cflags libmongoc-1.0)
./aggc

한 번의 호출에서 앞의 명령을 실행 데 연결 오류가 발생하는 경우 별도로 실행 수 있습니다.

6

집계된 결과에는 3개의 문서가 포함되어 있습니다. 문서는 "ENGINEER"라는 직업을 가진 사람 3명을 가장 나이 어린 사람부터 나이 많은 사람 순으로 표시합니다. 결과에서는 _idaddress 필드가 생략됩니다.

{ "person_id" : "7363626383", "firstname" : "Carl", "lastname" : "Simmons", "dateofbirth" : { "$date" : { "$numberLong" : "915250045000" } }, "vocation" : "ENGINEER" }
{ "person_id" : "6392529400", "firstname" : "Elise", "lastname" : "Smith", "dateofbirth" : { "$date" : { "$numberLong" : "653616727000" } }, "vocation" : "ENGINEER" }
{ "person_id" : "1723338115", "firstname" : "Olive", "lastname" : "Ranieri", "dateofbirth" : { "$date" : { "$numberLong" : "485113500000" } }, "gender" : "FEMALE", "vocation" : "ENGINEER" }
1

먼저 $match vocation 필드 값이 인 문서를 찾는 단계를 "ENGINEER" 추가합니다.

pipeline.match(bsoncxx::from_json(R"({
"vocation": "ENGINEER"
})"));
2

다음으로 필드 기준으로 $sort 문서를 내림차순으로 정렬하는 단계를 dateofbirth 추가하여 가장 어린 사람을 먼저 나열합니다.

pipeline.sort(bsoncxx::from_json(R"({
"dateofbirth": -1
})"));
3

다음으로, 파이프라인에 $limit 단계를 추가하여 결과에 처음 3개의 문서만 출력합니다.

pipeline.limit(3);
4

마지막으로 $unset 단계를 추가합니다. $unset 단계는 결과 문서에서 불필요한 필드를 제거합니다.

pipeline.append_stage(bsoncxx::from_json(R"({
"$unset": ["_id", "address"]
})"));

다른 필드가 있는 문서가 컬렉션에 추가되는 경우 집계 파이프라인이 수정되지 않도록 하려면 $project 대신 $unset 연산자를 사용합니다.

5

persons collection에서 애그리게이션을 수행하려면 애플리케이션 끝에 다음 코드를 추가하세요.

auto cursor = persons.aggregate(pipeline);

마지막으로 셸 에서 다음 명령을 실행 애플리케이션 시작합니다.

c++ --std=c++17 agg-tutorial.cpp $(pkg-config --cflags --libs libmongocxx) -o ./app.out
./app.out
6

집계된 결과에는 3개의 문서가 포함되어 있습니다. 문서는 "ENGINEER"라는 직업을 가진 사람 3명을 가장 나이 어린 사람부터 나이 많은 사람 순으로 표시합니다. 결과에서는 _idaddress 필드가 생략됩니다.

{ "person_id" : "7363626383", "firstname" : "Carl", "lastname" : "Simmons", "dateofbirth" : { "$date" : "1999-01-01T00:00:35Z" }, "vocation" : "ENGINEER" }
{ "person_id" : "1723338115", "firstname" : "Olive", "lastname" : "Ranieri", "dateofbirth" : { "$date" : "1985-05-21T13:14:30Z" }, "gender" : "FEMALE", "vocation" : "ENGINEER" }
{ "person_id" : "6392529400", "firstname" : "Elise", "lastname" : "Smith", "dateofbirth" : { "$date" : "1970-01-08T04:29:07.927Z" }, "vocation" : "ENGINEER" }
1

먼저 컬렉션 persons 에서 $match 집계 시작하고 필드 값이 인 문서를 찾는 단계를 Vocation "ENGINEER"연결합니다.

var results = persons.Aggregate()
.Match(p => p.Vocation == "ENGINEER")
2

다음으로 필드 기준으로 $sort 문서를 내림차순으로 정렬하는 단계를 DateOfBirth 추가하여 가장 어린 사람을 먼저 나열합니다.

.Sort(Builders<Person>.Sort.Descending(p => p.DateOfBirth))
3

다음으로, 파이프라인에 $limit 단계를 추가하여 결과에 처음 3개의 문서만 출력합니다.

.Limit(3)
4

마지막으로 $project 단계를 추가합니다. $project 단계에서는 결과 문서에서 불필요한 필드를 제외합니다.

.Project(Builders<Person>.Projection
.Exclude(p => p.Address)
.Exclude(p => p.Id)
);
5

마지막으로 IDE에서 애플리케이션 실행 하고 결과를 검사합니다.

집계된 결과에는 3개의 문서가 포함되어 있습니다. 문서는 "ENGINEER"라는 직업을 가진 사람 3명을 가장 나이 어린 사람부터 나이 많은 사람 순으로 표시합니다. 결과에서는 _idAddress 필드가 생략됩니다.

{ "PersonId" : "7363626383", "FirstName" : "Carl", "LastName" : "Simmons", "DateOfBirth" : { "$date" : "1998-12-26T13:13:55Z" }, "Vocation" : "ENGINEER" }
{ "PersonId" : "1723338115", "FirstName" : "Olive", "LastName" : "Ranieri", "DateOfBirth" : { "$date" : "1985-05-12T23:14:30Z" }, "Gender" : "FEMALE", "Vocation" : "ENGINEER" }
{ "PersonId" : "6392529400", "FirstName" : "Elise", "LastName" : "Smith", "DateOfBirth" : { "$date" : "1972-01-13T09:32:07Z" }, "Vocation" : "ENGINEER" }
1

먼저 $match vocation 필드 값이 인 문서를 찾는 단계를 "ENGINEER" 추가합니다.

matchStage := bson.D{{Key: "$match", Value: bson.D{{Key: "vocation", Value: "ENGINEER"}}}}
2

다음으로 필드 기준으로 $sort 문서를 내림차순으로 정렬하는 단계를 dateofbirth 추가하여 가장 어린 사람을 먼저 나열합니다.

sortStage := bson.D{{Key: "$sort", Value: bson.D{{Key: "dateofbirth", Value: -1}}}}
3

다음으로, 파이프라인에 $limit 단계를 추가하여 결과에 처음 3개의 문서만 출력합니다.

limitStage := bson.D{{Key: "$limit", Value: 3}}
4

마지막으로 $unset 단계를 추가합니다. $unset 단계는 결과 문서에서 불필요한 필드를 제거합니다.

unsetStage := bson.D{{Key: "$unset", Value: bson.A{"_id", "address"}}}

다른 필드가 있는 문서가 컬렉션에 추가되는 경우 집계 파이프라인이 수정되지 않도록 하려면 $project 대신 $unset 연산자를 사용합니다.

5

persons collection에서 애그리게이션을 수행하려면 애플리케이션 끝에 다음 코드를 추가하세요.

pipeline := mongo.Pipeline{matchStage, sortStage, limitStage, unsetStage}
cursor, err := persons.Aggregate(context.TODO(), pipeline)

마지막으로 shell에서 다음 명령을 실행하여 애플리케이션을 시작합니다.

go run agg_tutorial.go
6

집계된 결과에는 3개의 문서가 포함되어 있습니다. 문서는 "ENGINEER"라는 직업을 가진 사람 3명을 가장 나이 어린 사람부터 나이 많은 사람 순으로 표시합니다. 결과에서는 _idaddress 필드가 생략됩니다.

{"person_id":"7363626383","firstname":"Carl","lastname":"Simmons","dateofbirth":{"$date":"1998-12-26T13:13:55Z"},"vocation":"ENGINEER"}
{"person_id":"1723338115","firstname":"Olive","lastname":"Ranieri","gender":"FEMALE","dateofbirth":{"$date":"1985-05-12T23:14:30Z"},"vocation":"ENGINEER"}
{"person_id":"6392529400","firstname":"Elise","lastname":"Smith","dateofbirth":{"$date":"1972-01-13T09:32:07Z"},"vocation":"ENGINEER"}
1

먼저 $match vocation 필드 값이 인 문서를 찾는 단계를 "ENGINEER" 추가합니다.

pipeline.add(Aggregates.match(Filters.eq("vocation", "ENGINEER")));
2

다음으로 필드 기준으로 $sort 문서를 내림차순으로 정렬하는 단계를 dateofbirth 추가하여 가장 어린 사람을 먼저 나열합니다.

pipeline.add(Aggregates.sort(Sorts.descending("dateofbirth")));
3

다음으로, 파이프라인에 $limit 단계를 추가하여 결과에 처음 3개의 문서만 출력합니다.

pipeline.add(Aggregates.limit(3));
4

마지막으로 $unset 단계를 추가합니다. $unset 단계는 결과 문서에서 불필요한 필드를 제거합니다.

pipeline.add(Aggregates.unset("_id", "address"));

다른 필드가 있는 문서가 컬렉션에 추가되는 경우 집계 파이프라인이 수정되지 않도록 하려면 $project 대신 $unset 연산자를 사용합니다.

5

persons collection에서 애그리게이션을 수행하려면 애플리케이션 끝에 다음 코드를 추가하세요.

AggregateIterable<Document> aggregationResult = persons.aggregate(pipeline);

마지막으로 IDE에서 애플리케이션 실행 .

6

집계된 결과에는 3개의 문서가 포함되어 있습니다. 문서는 "ENGINEER"라는 직업을 가진 사람 3명을 가장 나이 어린 사람부터 나이 많은 사람 순으로 표시합니다. 결과에서는 _idaddress 필드가 생략됩니다.

{"person_id": "7363626383", "firstname": "Carl", "lastname": "Simmons", "dateofbirth": {"$date": "1998-12-26T13:13:55Z"}, "vocation": "ENGINEER"}
{"person_id": "1723338115", "firstname": "Olive", "lastname": "Ranieri", "dateofbirth": {"$date": "1985-05-12T23:14:30Z"}, "gender": "FEMALE", "vocation": "ENGINEER"}
{"person_id": "6392529400", "firstname": "Elise", "lastname": "Smith", "dateofbirth": {"$date": "1972-01-13T09:32:07Z"}, "vocation": "ENGINEER"}
1

먼저 $match vocation 필드 값이 인 문서를 찾는 단계를 "ENGINEER" 추가합니다.

pipeline.add(Aggregates.match(Filters.eq(Person::vocation.name, "ENGINEER")))
2

다음으로 필드 기준으로 $sort 문서를 내림차순으로 정렬하는 단계를 dateOfBirth 추가하여 가장 어린 사람을 먼저 나열합니다.

pipeline.add(Aggregates.sort(Sorts.descending(Person::dateOfBirth.name)))
3

다음으로, 파이프라인에 $limit 단계를 추가하여 결과에 처음 3개의 문서만 출력합니다.

pipeline.add(Aggregates.limit(3))
4

마지막으로 $unset 단계를 추가합니다. $unset 단계는 결과 문서에서 불필요한 필드를 제거합니다.

pipeline.add(Aggregates.unset("_id", Person::address.name))

다른 필드가 있는 문서가 컬렉션에 추가되는 경우 집계 파이프라인이 수정되지 않도록 하려면 $project 대신 $unset 연산자를 사용합니다.

5

persons collection에서 애그리게이션을 수행하려면 애플리케이션 끝에 다음 코드를 추가하세요.

val aggregationResult = persons.aggregate<Document>(pipeline)

마지막으로 IDE에서 애플리케이션 실행 .

6

집계된 결과에는 3개의 문서가 포함되어 있습니다. 문서는 "ENGINEER"라는 직업을 가진 사람 3명을 가장 나이 어린 사람부터 나이 많은 사람 순으로 표시합니다. 결과에서는 _idaddress 필드가 생략됩니다.

Document{{personID=7363626383, firstname=Carl, lastname=Simmons, dateOfBirth=Sat Dec 26 08:13:55 EST 1998, vocation=ENGINEER}}
Document{{personID=1723338115, firstname=Olive, lastname=Ranieri, dateOfBirth=Sun May 12 19:14:30 EDT 1985, vocation=ENGINEER, gender=FEMALE}}
Document{{personID=6392529400, firstname=Elise, lastname=Smith, dateOfBirth=Thu Jan 13 04:32:07 EST 1972, vocation=ENGINEER}}
1

먼저 $match vocation 필드 값이 인 문서를 찾는 단계를 "ENGINEER" 추가합니다.

pipeline.push({
$match: {
vocation: "ENGINEER",
},
});
2

다음으로 필드 기준으로 $sort 문서를 내림차순으로 정렬하는 단계를 dateofbirth 추가하여 가장 어린 사람을 먼저 나열합니다.

pipeline.push({
$sort: {
dateofbirth: -1,
},
});
3

다음으로, 파이프라인에 $limit 단계를 추가하여 결과에 처음 3개의 문서만 출력합니다.

pipeline.push({
$limit: 3,
});
4

마지막으로 $unset 단계를 추가합니다. $unset 단계는 결과 문서에서 불필요한 필드를 제거합니다.

pipeline.push({
$unset: ["_id", "address"],
});

다른 필드가 있는 문서가 컬렉션에 추가되는 경우 집계 파이프라인이 수정되지 않도록 하려면 $project 대신 $unset 연산자를 사용합니다.

5

persons collection에서 애그리게이션을 수행하려면 애플리케이션 끝에 다음 코드를 추가하세요.

const aggregationResult = await persons.aggregate(pipeline);

마지막으로 shell에서 다음 명령을 실행하여 애플리케이션을 시작합니다.

node agg_tutorial.js
6

집계된 결과에는 3개의 문서가 포함되어 있습니다. 문서는 "ENGINEER"라는 직업을 가진 사람 3명을 가장 나이 어린 사람부터 나이 많은 사람 순으로 표시합니다. 결과에서는 _idaddress 필드가 생략됩니다.

{
person_id: '7363626383',
firstname: 'Carl',
lastname: 'Simmons',
dateofbirth: 1998-12-26T13:13:55.000Z,
vocation: 'ENGINEER'
}
{
person_id: '1723338115',
firstname: 'Olive',
lastname: 'Ranieri',
dateofbirth: 1985-05-12T23:14:30.000Z,
gender: 'FEMALE',
vocation: 'ENGINEER'
}
{
person_id: '6392529400',
firstname: 'Elise',
lastname: 'Smith',
dateofbirth: 1972-01-13T09:32:07.000Z,
vocation: 'ENGINEER'
}
1

인스턴스 Pipeline $match 에서 필드 값이 인 문서를 찾는 단계를 vocation "ENGINEER" 만듭니다.

Stage::match(vocation: 'ENGINEER'),
2

다음으로 필드 기준으로 문서를 $sort 내림차순으로 dateofbirth 정렬하여 가장 어린 사람을 먼저 나열하는 단계를 만듭니다.

Stage::sort(dateofbirth: Sort::Desc),
3

다음으로, 파이프라인에 대한 $limit 단계를 생성하여 결과에 처음 3개의 문서만 출력합니다.

Stage::limit(3),
4

마지막으로 $unset 단계를 만듭니다. $unset 단계는 결과 문서에서 불필요한 필드를 제거합니다.

Stage::unset('_id', 'address')

다른 필드가 있는 문서가 컬렉션에 추가되는 경우 집계 파이프라인이 수정되지 않도록 하려면 $project 대신 $unset 연산자를 사용합니다.

5

persons collection에서 애그리게이션을 수행하려면 애플리케이션 끝에 다음 코드를 추가하세요.

$cursor = $persons->aggregate($pipeline);

마지막으로 shell에서 다음 명령을 실행하여 애플리케이션을 시작합니다.

php agg_tutorial.php
6

집계된 결과에는 3개의 문서가 포함되어 있습니다. 문서는 "ENGINEER"라는 직업을 가진 사람 3명을 가장 나이 어린 사람부터 나이 많은 사람 순으로 표시합니다. 결과에서는 _idaddress 필드가 생략됩니다.

{
"person_id": "7363626383",
"firstname": "Carl",
"lastname": "Simmons",
"dateofbirth": {
"$date": {
"$numberLong": "914678035000"
}
},
"vocation": "ENGINEER"
}
{
"person_id": "1723338115",
"firstname": "Olive",
"lastname": "Ranieri",
"gender": "FEMALE",
"dateofbirth": {
"$date": {
"$numberLong": "484787670000"
}
},
"vocation": "ENGINEER"
}
{
"person_id": "6392529400",
"firstname": "Elise",
"lastname": "Smith",
"dateofbirth": {
"$date": {
"$numberLong": "64143127000"
}
},
"vocation": "ENGINEER"
}
1

인스턴스 Pipeline $match 에서 필드 값이 인 문서를 찾는 단계를 vocation "ENGINEER" 만듭니다.

pipeline.append({"$match": {"vocation": "ENGINEER"}})
2

다음으로 필드 기준으로 문서를 $sort 내림차순으로 dateofbirth 정렬하여 가장 어린 사람을 먼저 나열하는 단계를 만듭니다.

pipeline.append({"$sort": {"dateofbirth": -1}})
3

다음으로, 파이프라인에 대한 $limit 단계를 생성하여 결과에 처음 3개의 문서만 출력합니다.

pipeline.append({"$limit": 3})
4

마지막으로 $unset 단계를 만듭니다. $unset 단계는 결과 문서에서 불필요한 필드를 제거합니다.

pipeline.append({"$unset": ["_id", "address"]})

다른 필드가 있는 문서가 컬렉션에 추가되는 경우 집계 파이프라인이 수정되지 않도록 하려면 $project 대신 $unset 연산자를 사용합니다.

5

persons collection에서 애그리게이션을 수행하려면 애플리케이션 끝에 다음 코드를 추가하세요.

aggregation_result = person_coll.aggregate(pipeline)

마지막으로 shell에서 다음 명령을 실행하여 애플리케이션을 시작합니다.

python3 agg_tutorial.py
6

집계된 결과에는 3개의 문서가 포함되어 있습니다. 문서는 "ENGINEER"라는 직업을 가진 사람 3명을 가장 나이 어린 사람부터 나이 많은 사람 순으로 표시합니다. 결과에서는 _idaddress 필드가 생략됩니다.

{'person_id': '7363626383', 'firstname': 'Carl', 'lastname': 'Simmons', 'dateofbirth': datetime.datetime(1998, 12, 26, 13, 13, 55), 'vocation': 'ENGINEER'}
{'person_id': '1723338115', 'firstname': 'Olive', 'lastname': 'Ranieri', 'dateofbirth': datetime.datetime(1985, 5, 12, 23, 14, 30), 'gender': 'FEMALE', 'vocation': 'ENGINEER'}
{'person_id': '6392529400', 'firstname': 'Elise', 'lastname': 'Smith', 'dateofbirth': datetime.datetime(1972, 1, 13, 9, 32, 7), 'vocation': 'ENGINEER'}
1

먼저 $match vocation 필드 값이 인 문서를 찾는 단계를 "ENGINEER" 추가합니다.

{ "$match": { "vocation": "ENGINEER" } },
2

다음으로 필드 기준으로 $sort 문서를 내림차순으로 정렬하는 단계를 dateofbirth 추가하여 가장 어린 사람을 먼저 나열합니다.

{ "$sort": { "dateofbirth": -1 } },
3

다음으로, 파이프라인에 $limit 단계를 추가하여 결과에 처음 3개의 문서만 출력합니다.

{ "$limit": 3 },
4

마지막으로 $unset 단계를 추가합니다. $unset 단계는 결과 문서에서 불필요한 필드를 제거합니다.

{ "$unset": ["_id", "address"] },

다른 필드가 있는 문서가 컬렉션에 추가되는 경우 집계 파이프라인이 수정되지 않도록 하려면 $project 대신 $unset 연산자를 사용합니다.

5

persons collection에서 애그리게이션을 수행하려면 애플리케이션 끝에 다음 코드를 추가하세요.

aggregation_result = persons.aggregate(pipeline)

마지막으로 shell에서 다음 명령을 실행하여 애플리케이션을 시작합니다.

node agg_tutorial.rb
6

집계된 결과에는 3개의 문서가 포함되어 있습니다. 문서는 "ENGINEER"라는 직업을 가진 사람 3명을 가장 나이 어린 사람부터 나이 많은 사람 순으로 표시합니다. 결과에서는 _idaddress 필드가 생략됩니다.

{"person_id"=>"7363626383", "firstname"=>"Carl", "lastname"=>"Simmons", "dateofbirth"=>1998-12-26 13:13:55 UTC, "vocation"=>"ENGINEER"}
{"person_id"=>"1723338115", "firstname"=>"Olive", "lastname"=>"Ranieri", "dateofbirth"=>1985-05-12 23:14:30 UTC, "gender"=>"FEMALE", "vocation"=>"ENGINEER"}
{"person_id"=>"6392529400", "firstname"=>"Elise", "lastname"=>"Smith", "dateofbirth"=>1972-01-13 09:32:07 UTC, "vocation"=>"ENGINEER"}
1

먼저 $match vocation 필드 값이 인 문서를 찾는 단계를 "ENGINEER" 추가합니다.

pipeline.push(doc! { "$match": { "vocation": "ENGINEER" } });
2

다음으로 필드 기준으로 $sort 문서를 내림차순으로 정렬하는 단계를 dateofbirth 추가하여 가장 어린 사람을 먼저 나열합니다.

pipeline.push(doc! { "$sort": { "dateofbirth": -1 } });
3

다음으로, 파이프라인에 $limit 단계를 추가하여 결과에 처음 3개의 문서만 출력합니다.

pipeline.push(doc! { "$limit": 3 });
4

마지막으로 $unset 단계를 추가합니다. $unset 단계는 결과 문서에서 불필요한 필드를 제거합니다.

pipeline.push(doc! { "$unset": ["_id", "address"] });

다른 필드가 있는 문서가 컬렉션에 추가되는 경우 집계 파이프라인이 수정되지 않도록 하려면 $project 대신 $unset 연산자를 사용합니다.

5

persons collection에서 애그리게이션을 수행하려면 애플리케이션 끝에 다음 코드를 추가하세요.

let mut cursor = persons.aggregate(pipeline).await?;

마지막으로 shell에서 다음 명령을 실행하여 애플리케이션을 시작합니다.

cargo run
6

집계된 결과에는 3개의 문서가 포함되어 있습니다. 문서는 "ENGINEER"라는 직업을 가진 사람 3명을 가장 나이 어린 사람부터 나이 많은 사람 순으로 표시합니다. 결과에서는 _idaddress 필드가 생략됩니다.

Document({"person_id": String("7363626383"), "firstname": String("Carl"), "lastname": String("Simmons"), "dateofbirth": DateTime(1998-12-26 13:13:55.0 +00:00:00), "vocation": String("ENGINEER")})
Document({"person_id": String("1723338115"), "firstname": String("Olive"), "lastname": String("Ranieri"), "gender": String("FEMALE"), "dateofbirth": DateTime(1985-05-12 23:14:30.0 +00:00:00), "vocation": String("ENGINEER")})
Document({"person_id": String("6392529400"), "firstname": String("Elise"), "lastname": String("Smith"), "dateofbirth": DateTime(1972-01-13 9:32:07.0 +00:00:00), "vocation": String("ENGINEER")})
1

먼저 $match vocation 필드 값이 인 문서를 찾는 단계를 "ENGINEER" 추가합니다.

Aggregates.filter(Filters.equal("vocation", "ENGINEER")),
2

다음으로 필드 기준으로 $sort 문서를 내림차순으로 정렬하는 단계를 dateofbirth 추가하여 가장 어린 사람을 먼저 나열합니다.

Aggregates.sort(Sorts.descending("dateofbirth")),
3

다음으로, 파이프라인에 $limit 단계를 추가하여 결과에 처음 3개의 문서만 출력합니다.

Aggregates.limit(3),
4

마지막으로 $unset 단계를 추가합니다. $unset 단계는 결과 문서에서 불필요한 필드를 제거합니다.

Aggregates.unset("_id", "address")

다른 필드가 있는 문서가 컬렉션에 추가되는 경우 집계 파이프라인이 수정되지 않도록 하려면 $project 대신 $unset 연산자를 사용합니다.

5

persons collection에서 애그리게이션을 수행하려면 애플리케이션 끝에 다음 코드를 추가하세요.

persons.aggregate(pipeline)
.subscribe((doc: Document) => println(doc.toJson()),
(e: Throwable) => println(s"Error: $e"))

마지막으로 IDE에서 애플리케이션 실행 .

6

집계된 결과에는 3개의 문서가 포함되어 있습니다. 문서는 "ENGINEER"라는 직업을 가진 사람 3명을 가장 나이 어린 사람부터 나이 많은 사람 순으로 표시합니다. 결과에서는 _idaddress 필드가 생략됩니다.

{"person_id": "7363626383", "firstname": "Carl", "lastname": "Simmons", "dateofbirth": {"$date": "1998-12-26T18:13:55Z"}, "vocation": "ENGINEER"}
{"person_id": "1723338115", "firstname": "Olive", "lastname": "Ranieri", "dateofbirth": {"$date": "1985-05-13T03:14:30Z"}, "gender": "FEMALE", "vocation": "ENGINEER"}
{"person_id": "6392529400", "firstname": "Elise", "lastname": "Smith", "dateofbirth": {"$date": "1972-01-13T14:32:07Z"}, "vocation": "ENGINEER"}

돌아가기

파이프라인 튜토리얼

이 페이지의 내용