This tutorial illustrates how to construct an aggregation pipeline, perform the aggregation on a collection, and display the results using the language of your choice.本教程说明了如何构建聚合管道,对集合执行聚合,并使用您选择的语言显示结果。
About This Task关于此任务
This tutorial demonstrates how to query for a specific subset of documents in a collection.本教程演示如何查询集合中的特定文档子集。
The aggregation pipeline performs the following operations:聚合管道执行以下操作:
Matches a subset of documents by a field value根据字段值匹配文档子集Formats result documents格式化结果文档
Before You Begin开始之前
➤ Use the Select your language drop-down menu in the upper-right to set the language of the following examples or select MongoDB Shell.使用右上角的“选择语言”下拉菜单设置以下示例的语言,或选择MongoDB Shell。
MongoDB Shell
This example uses a 此示例使用persons collection, which contains documents describing each person's name, date of birth, vocation, and other details. The aggregation selects documents based on whether their field values match specified criteria.persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据文档的字段值是否与指定条件匹配来选择文档。
To create the 要创建persons collection, use the insertMany() method:persons集合,请使用insertMany()方法:
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
Create the Template App创建模板应用程序
Before you begin following this aggregation tutorial, you must set up a new C app. You can use this app to connect to a MongoDB deployment, insert sample data into MongoDB, and run the aggregation pipeline.在开始学习此聚合教程之前,您必须设置一个新的C应用程序。您可以使用此应用程序连接到MongoDB部署,将示例数据插入MongoDB,并运行聚合管道。
Tip
To learn how to install the driver and connect to MongoDB, see the Get Started with the C Driver guide.要了解如何安装驱动程序并连接到MongoDB,请参阅C驱动程序入门指南。
To learn more about performing aggregations in the C Driver, see the Aggregation guide.要了解有关在C驱动程序中执行聚合的更多信息,请参阅聚合指南。
After you install the driver, create a file called 安装驱动程序后,创建一个名为agg-tutorial.c. Paste the following code in this file to create an app template for the aggregation tutorials.agg-tutorial.c的文件。将以下代码粘贴到此文件中,为聚合教程创建应用程序模板。
Important
In the following code, read the code comments to find the sections of the code that you must modify for the tutorial you are following.在下面的代码中,阅读代码注释,找到您必须为正在学习的教程修改的代码部分。
If you attempt to run the code without making any changes, you will encounter a connection error.如果您尝试在不进行任何更改的情况下运行代码,您将遇到连接错误。
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;
}
For every tutorial, you must replace the connection string placeholder with your deployment's connection string.对于每个教程,您必须将连接字符串占位符替换为部署的连接字符串。
Tip
To learn how to locate your deployment's connection string, see the Create a Connection String step of the C Get Started guide.要了解如何定位部署的连接字符串,请参阅《C入门》指南的创建连接字符串步骤。
For example, if your connection string is 例如,如果连接字符串是"mongodb+srv://mongodb-example:27017", your connection string assignment resembles the following:"mongodb+srv://mongodb-example:27017",连接字符串分配类似于以下内容:
char *uri = "mongodb+srv://mongodb-example:27017";Create the Collection创建集合
This example uses a 此示例使用persons collection, which contains documents describing each person's name, date of birth, vocation, and other details. The aggregation selects documents based on whether their field values match specified criteria.persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据文档的字段值是否与指定条件匹配来选择文档。
To create the 要创建persons collection and insert the sample data, add the following code to your application: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++11
Create the Template App创建模板应用程序
Before you begin following an aggregation tutorial, you must set up a new C++ app. You can use this app to connect to a MongoDB deployment, insert sample data into MongoDB, and run the aggregation pipeline.在开始学习聚合教程之前,您必须设置一个新的C++应用程序。您可以使用此应用程序连接到MongoDB部署,将示例数据插入MongoDB,并运行聚合管道。
Tip
To learn how to install the driver and connect to MongoDB, see the Get Started with C++ tutorial.要了解如何安装驱动程序并连接到MongoDB,请参阅C++入门教程。
To learn more about using the C++ driver, see the API documentation.要了解有关使用C++驱动程序的更多信息,请参阅API文档。
To learn more about performing aggregations in the C++ Driver, see the Aggregation guide.要了解有关在C++驱动程序中执行聚合的更多信息,请参阅聚合指南。
After you install the driver, create a file called 安装驱动程序后,创建一个名为agg-tutorial.cpp. Paste the following code in this file to create an app template for the aggregation tutorials.agg-tutorial.cpp的文件。将以下代码粘贴到此文件中,为聚合教程创建应用程序模板。
Important
In the following code, read the code comments to find the sections of the code that you must modify for the tutorial you are following.在下面的代码中,阅读代码注释,找到您必须为正在学习的教程修改的代码部分。
If you attempt to run the code without making any changes, you will encounter a connection error.如果您尝试在不进行任何更改的情况下运行代码,您将遇到连接错误。
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;
}
}
For every tutorial, you must replace the connection string placeholder with your deployment's connection string.对于每个教程,您必须将连接字符串占位符替换为部署的连接字符串。
Tip
To learn how to locate your deployment's connection string, see the Create a Connection String step of the C++ Get Started tutorial.要了解如何定位部署的连接字符串,请参阅C++入门教程的创建连接字符串步骤。
For example, if your connection string is 例如,如果连接字符串是"mongodb+srv://mongodb-example:27017", your connection string assignment resembles the following:"mongodb+srv://mongodb-example:27017",连接字符串分配类似于以下内容:
mongocxx::uri uri{"mongodb+srv://mongodb-example:27017"};Create the Collection创建集合
This example uses a 此示例使用persons collection, which contains documents describing each person's name, date of birth, vocation, and other details. The aggregation selects documents based on whether their field values match specified criteria.persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据文档的字段值是否与指定条件匹配来选择文档。
To create the 要创建persons collection and insert the sample data, add the following code to your application: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 exceptionC#
Create the Template App创建模板应用程序
Before you begin following this aggregation tutorial, you must set up a new C#/.NET app. You can use this app to connect to a MongoDB deployment, insert sample data into MongoDB, and run the aggregation pipeline.在开始学习此聚合教程之前,您必须设置一个新的C#/NET应用程序。您可以使用此应用程序连接到MongoDB部署,将示例数据插入MongoDB,并运行聚合管道。
Tip
To learn how to install the driver and connect to MongoDB, see the C#/.NET Driver Quick Start guide.要了解如何安装驱动程序并连接到MongoDB,请参阅C#/.NET驱动程序快速入门指南。
To learn more about performing aggregations in the C#/.NET Driver, see the Aggregation guide.要了解有关在C#/NET驱动程序中执行聚合的更多信息,请参阅聚合指南。
After you install the driver, paste the following code into your 安装驱动程序后,将以下代码粘贴到Program.cs file to create an app template for the aggregation tutorials.Program.cs文件中,为聚合教程创建应用程序模板。
Important
In the following code, read the code comments to find the sections of the code that you must modify for the tutorial you are following.在下面的代码中,阅读代码注释,找到您必须为正在学习的教程修改的代码部分。
If you attempt to run the code without making any changes, you will encounter a connection error.如果您尝试在不进行任何更改的情况下运行代码,您将遇到连接错误。
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
// 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);
}
For every tutorial, you must replace the connection string placeholder with your deployment's connection string.对于每个教程,您必须将连接字符串占位符替换为部署的连接字符串。
Tip
To learn how to locate your deployment's connection string, see the Set Up a Free Tier Cluster in Atlas step of the C# Quick Start guide.要了解如何定位部署的连接字符串,请参阅《C#快速入门》指南的在Atlas中设置免费层集群步骤。
For example, if your connection string is 例如,如果连接字符串是"mongodb+srv://mongodb-example:27017", your connection string assignment resembles the following:"mongodb+srv://mongodb-example:27017",连接字符串分配类似于以下内容:
var uri = "mongodb+srv://mongodb-example:27017";Create the Collection创建集合
This example uses a 此示例使用persons collection, which contains documents describing each person's name, date of birth, vocation, and other details. The aggregation selects documents based on whether their field values match specified criteria.persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据文档的字段值是否与指定条件匹配来选择文档。
First, create C# classes to model the data in the 首先,创建C#类来对persons collection:persons集合中的数据进行建模:
public class Person
{
[]
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; }
[]
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; } = "";
}
To create the 要创建persons collection and insert the sample data, add the following code to your application:persons集合并插入示例数据,请将以下代码添加到应用程序中:
var persons = aggDB.GetCollection<Person>("persons");
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
Create the Template App创建模板应用程序
Before you begin following this aggregation tutorial, you must set up a new Go app. You can use this app to connect to a MongoDB deployment, insert sample data into MongoDB, and run the aggregation pipeline.在开始学习此聚合教程之前,您必须设置一个新的Go应用程序。您可以使用此应用程序连接到MongoDB部署,将示例数据插入MongoDB,并运行聚合管道。
Tip
To learn how to install the driver and connect to MongoDB, see the Go Driver Quick Start guide.要了解如何安装驱动程序并连接到MongoDB,请参阅Go驱动程序快速入门指南。
To learn more about performing aggregations in the Go Driver, see the Aggregation guide.要了解有关在Go驱动程序中执行聚合的更多信息,请参阅聚合指南。
After you install the driver, create a file called 安装驱动程序后,创建一个名为agg_tutorial.go. Paste the following code in this file to create an app template for the aggregation tutorials.agg_tutorial.go的文件。将以下代码粘贴到此文件中,为聚合教程创建应用程序模板。
Important
In the following code, read the code comments to find the sections of the code that you must modify for the tutorial you are following.在下面的代码中,阅读代码注释,找到您必须为正在学习的教程修改的代码部分。
If you attempt to run the code without making any changes, you will encounter a connection error.如果您尝试在不进行任何更改的情况下运行代码,您将遇到连接错误。
package main
import (
"context"
"fmt"
"log"
"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() {
ctx := context.Background()
// 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(ctx); 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(cxt, 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(ctx, pipeline)
if err != nil {
log.Fatal(err)
}
defer func() {
if err := cursor.Close(ctx); err != nil {
log.Fatalf("failed to close cursor: %v", err)
}
}()
// Decode the aggregation results.
var results []bson.D
if err = cursor.All(ctx, &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))
}
}
For every tutorial, you must replace the connection string placeholder with your deployment's connection string.对于每个教程,您必须将连接字符串占位符替换为部署的连接字符串。
Tip
To learn how to locate your deployment's connection string, see the Create a MongoDB Cluster step of the Go Quick Start guide.要了解如何定位部署的连接字符串,请参阅Go快速入门指南的创建MongoDB集群步骤。
For example, if your connection string is 例如,如果连接字符串是"mongodb+srv://mongodb-example:27017", your connection string assignment resembles the following:"mongodb+srv://mongodb-example:27017",连接字符串分配类似于以下内容:
const uri = "mongodb+srv://mongodb-example:27017";Create the Collection创建集合
This example uses a 此示例使用persons collection, which contains documents describing each person's name, date of birth, vocation, and other details. The aggregation selects documents based on whether their field values match specified criteria.persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据文档的字段值是否与指定条件匹配来选择文档。
First, create Go structs to model the data in the 首先,创建Go结构体来对persons collection: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
}
To create the 要创建persons collection and insert the sample data, add the following code to your application:persons集合并插入示例数据,请将以下代码添加到应用程序中:
persons := aggDB.Collection("persons")
_, err = persons.InsertMany(ctx, []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(Sync)
Create the Template App创建模板应用程序
Before you begin following an aggregation tutorial, you must set up a new Java app. You can use this app to connect to a MongoDB deployment, insert sample data into MongoDB, and run the aggregation pipeline.在开始学习聚合教程之前,您必须设置一个新的Java应用程序。您可以使用此应用程序连接到MongoDB部署,将示例数据插入MongoDB,并运行聚合管道。
Tip
To learn how to install the driver and connect to MongoDB, see the Get Started with the Java Driver guide.要了解如何安装驱动程序并连接到MongoDB,请参阅Java驱动程序入门指南。
To learn more about performing aggregations in the Java Sync Driver, see the Aggregation guide.要了解有关在Java同步驱动程序中执行聚合的更多信息,请参阅聚合指南。
After you install the driver, create a file called 安装驱动程序后,创建一个名为AggTutorial.java. Paste the following code in this file to create an app template for the aggregation tutorials.AggTutorial.java的文件。将以下代码粘贴到此文件中,为聚合教程创建应用程序模板。
Important
In the following code, read the code comments to find the sections of the code that you must modify for the tutorial you are following.在下面的代码中,阅读代码注释,找到您必须为正在学习的教程修改的代码部分。
If you attempt to run the code without making any changes, you will encounter a connection error.如果您尝试在不进行任何更改的情况下运行代码,您将遇到连接错误。
package org.example;
// Modify imports for each tutorial as needed.
import com.mongodb.client.*;
import com.mongodb.client.model.Accumulators;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Field;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Sorts;
import com.mongodb.client.model.Variable;
import org.bson.Document;
import org.bson.conversions.Bson;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
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 = ...
// 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());
}
}
}
}
For every tutorial, you must replace the connection string placeholder with your deployment's connection string.对于每个教程,您必须将连接字符串占位符替换为部署的连接字符串。
Tip
To learn how to locate your deployment's connection string, see the Create a Connection String step of the Java Sync Quick Start guide.要了解如何定位部署的连接字符串,请参阅《Java Sync快速入门》指南的创建连接字符串步骤。
For example, if your connection string is 例如,如果连接字符串是"mongodb+srv://mongodb-example:27017", your connection string assignment resembles the following:"mongodb+srv://mongodb-example:27017",连接字符串分配类似于以下内容:
String uri = "mongodb+srv://mongodb-example:27017";Create the Collection创建集合
This example uses a 此示例使用persons collection, which contains documents describing each person's name, date of birth, vocation, and other details. The aggregation selects documents based on whether their field values match specified criteria.persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据文档的字段值是否与指定条件匹配来选择文档。
To create the 要创建persons collection and insert the sample data, add the following code to your application:persons集合并插入示例数据,请将以下代码添加到应用程序中:
MongoDatabase aggDB = mongoClient.getDatabase("agg_tutorials_db");
MongoCollection<Document> persons = aggDB.getCollection("persons");
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(Coroutine)
Create the Template App创建模板应用程序
Before you begin following an aggregation tutorial, you must set up a new Kotlin app. You can use this app to connect to a MongoDB deployment, insert sample data into MongoDB, and run the aggregation pipeline.在开始学习聚合教程之前,您必须设置一个新的Kotlin应用程序。您可以使用此应用程序连接到MongoDB部署,将示例数据插入MongoDB,并运行聚合管道。
Tip
To learn how to install the driver and connect to MongoDB, see the Kotlin Driver Quick Start guide.要了解如何安装驱动程序并连接到MongoDB,请参阅Kotlin驱动程序快速入门指南。
To learn more about performing aggregations in the Kotlin Driver, see the Aggregation guide.要了解有关在Kotlin驱动程序中执行聚合的更多信息,请参阅聚合指南。
In addition to the driver, you must also add the following dependencies to your 除了驱动程序,您还必须将以下依赖项添加到build.gradle.kts file and reload your project: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")
}
After you install the driver, create a file called 安装驱动程序后,创建一个名为AggTutorial.kt. Paste the following code in this file to create an app template for the aggregation tutorials.AggTutorial.kt的文件。将以下代码粘贴到此文件中,为聚合教程创建应用程序模板。
Important
In the following code, read the code comments to find the sections of the code that you must modify for the tutorial you are following.在下面的代码中,阅读代码注释,找到您必须为正在学习的教程修改的代码部分。
If you attempt to run the code without making any changes, you will encounter a connection error.如果您尝试在不进行任何更改的情况下运行代码,您将遇到连接错误。
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.
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) }
}
}
For every tutorial, you must replace the connection string placeholder with your deployment's connection string.对于每个教程,您必须将连接字符串占位符替换为部署的连接字符串。
Tip
To learn how to locate your deployment's connection string, see the Connect to your Cluster step of the Kotlin Driver Quick Start guide.要了解如何定位部署的连接字符串,请参阅Kotlin驱动程序快速入门指南的连接到集群步骤。
For example, if your connection string is 例如,如果连接字符串是"mongodb+srv://mongodb-example:27017", your connection string assignment resembles the following:"mongodb+srv://mongodb-example:27017",连接字符串分配类似于以下内容:
val uri = "mongodb+srv://mongodb-example:27017"Create the Collection创建集合
This example uses a 此示例使用persons collection, which contains documents describing each person's name, date of birth, vocation, and other details. The aggregation selects documents based on whether their field values match specified criteria.persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据文档的字段值是否与指定条件匹配来选择文档。
First, create Kotlin data classes to model the data in the 首先,创建Kotlin数据类来对persons collection:persons集合中的数据进行建模:
data class Address(
val number: Int,
val street: String,
val city: String
)
data class Person(
val personID: String,
val firstname: String,
val lastname: String,
val dateOfBirth: LocalDateTime,
val vocation: String,
val address: Address,
val gender: String? = null
)
To create the 要创建persons collection and insert the sample data, add the following code to your application: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
Create the Template App创建模板应用程序
Before you begin following this aggregation tutorial, you must set up a new Node.js app. You can use this app to connect to a MongoDB deployment, insert sample data into MongoDB, and run the aggregation pipeline.在开始学习本聚合教程之前,您必须设置一个新的Node.js应用程序。您可以使用此应用程序连接到MongoDB部署,将示例数据插入MongoDB,并运行聚合管道。
Tip
To learn how to install the driver and connect to MongoDB, see the Node.js Driver Quick Start guide.要了解如何安装驱动程序并连接到MongoDB,请参阅Node.js驱动程序快速入门指南。
To learn more about performing aggregations in the Node.js Driver, see the Aggregation guide.要了解有关在Node.js驱动程序中执行聚合的更多信息,请参阅聚合指南。
After you install the driver, create a file to run the tutorial template. Paste the following code in this file to create an app template for the aggregation tutorials.安装驱动程序后,创建一个文件来运行教程模板。将以下代码粘贴到此文件中,为聚合教程创建应用程序模板。
Important
In the following code, read the code comments to find the sections of the code that you must modify for the tutorial you are following.在下面的代码中,阅读代码注释,找到您必须为正在学习的教程修改的代码部分。
If you attempt to run the code without making any changes, you will encounter a connection error.如果您尝试在不进行任何更改的情况下运行代码,您将遇到连接错误。
const { MongoClient } = require('mongodb');
// Replace the placeholder with your connection string.
const uri = '<connection-string>';
const client = new MongoClient(uri);
export 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);
For every tutorial, you must replace the connection string placeholder with your deployment's connection string.对于每个教程,您必须将连接字符串占位符替换为部署的连接字符串。
Tip
To learn how to locate your deployment's connection string, see the Create a Connection String step of the Node.js Quick Start guide.要了解如何定位部署的连接字符串,请参阅Node.js快速入门指南的创建连接字符串步骤。
For example, if your connection string is 例如,如果连接字符串是"mongodb+srv://mongodb-example:27017", your connection string assignment resembles the following:"mongodb+srv://mongodb-example:27017",连接字符串分配类似于以下内容:
const uri = "mongodb+srv://mongodb-example:27017";Create the Collection创建集合
This example uses a 此示例使用persons collection, which contains documents describing each person's name, date of birth, vocation, and other details. The aggregation selects documents based on whether their field values match specified criteria.persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据文档的字段值是否与指定条件匹配来选择文档。
To create the 要创建persons collection and insert the sample data, add the following code to your application:persons集合并插入示例数据,请将以下代码添加到应用程序中:
const persons = aggDB.collection('persons');
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
Create the Template App创建模板应用程序
Before you begin following this aggregation tutorial, you must set up a new PHP app. You can use this app to connect to a MongoDB deployment, insert sample data into MongoDB, and run the aggregation pipeline.在开始学习本聚合教程之前,您必须设置一个新的PHP应用程序。您可以使用此应用程序连接到MongoDB部署,将示例数据插入MongoDB,并运行聚合管道。
Tip
To learn how to install the PHP library and connect to MongoDB, see the Get Started with the PHP Library tutorial.要了解如何安装PHP库并连接到MongoDB,请参阅PHP库入门教程。
To learn more about performing aggregations in the PHP library, see the Aggregation guide.要了解有关在PHP库中执行聚合的更多信息,请参阅聚合指南。
After you install the library, create a file called 安装库后,创建一个名为agg_tutorial.php. Paste the following code in this file to create an app template for the aggregation tutorials.agg_tutorial.php的文件。将以下代码粘贴到此文件中,为聚合教程创建应用程序模板。
Important
In the following code, read the code comments to find the sections of the code that you must modify for the tutorial you are following.在下面的代码中,阅读代码注释,找到您必须为正在学习的教程修改的代码部分。
If you attempt to run the code without making any changes, you will encounter a connection error.如果您尝试在不进行任何更改的情况下运行代码,您将遇到连接错误。
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;
}
For every tutorial, you must replace the connection string placeholder with your deployment's connection string.对于每个教程,您必须将连接字符串占位符替换为部署的连接字符串。
Tip
To learn how to locate your deployment's connection string, see the Create a Connection String step of the Get Started with the PHP Library tutorial.要了解如何定位部署的连接字符串,请参阅PHP库入门教程的创建连接字符串步骤。
For example, if your connection string is 例如,如果连接字符串是"mongodb+srv://mongodb-example:27017", your connection string assignment resembles the following:"mongodb+srv://mongodb-example:27017",连接字符串分配类似于以下内容:
$uri = 'mongodb+srv://mongodb-example:27017';Create the Collection创建集合
This example uses a 此示例使用persons collection, which contains documents describing each person's name, date of birth, vocation, and other details. The aggregation selects documents based on whether their field values match specified criteria.persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据文档的字段值是否与指定条件匹配来选择文档。
To create the 要创建persons collection and insert the sample data, add the following code to your application: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
Create the Template App创建模板应用程序
Before you begin following this aggregation tutorial, you must set up a new Python app. You can use this app to connect to a MongoDB deployment, insert sample data into MongoDB, and run the aggregation pipeline.在开始学习本聚合教程之前,您必须设置一个新的Python应用程序。您可以使用此应用程序连接到MongoDB部署,将示例数据插入MongoDB,并运行聚合管道。
Tip
To learn how to install PyMongo and connect to MongoDB, see the Get Started with PyMongo tutorial.要了解如何安装PyMongo并连接到MongoDB,请参阅PyMongo入门教程。
To learn more about performing aggregations in PyMongo, see the Aggregation guide.要了解有关在PyMongo中执行聚合的更多信息,请参阅聚合指南。
After you install the library, create a file called 安装库后,创建一个名为agg_tutorial.py. Paste the following code in this file to create an app template for the aggregation tutorials.agg_tutorial.py的文件。将以下代码粘贴到此文件中,为聚合教程创建应用程序模板。
Important
In the following code, read the code comments to find the sections of the code that you must modify for the tutorial you are following.在下面的代码中,阅读代码注释,找到您必须为正在学习的教程修改的代码部分。
If you attempt to run the code without making any changes, you will encounter a connection error.如果您尝试在不进行任何更改的情况下运行代码,您将遇到连接错误。
# 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()
For every tutorial, you must replace the connection string placeholder with your deployment's connection string.对于每个教程,您必须将连接字符串占位符替换为部署的连接字符串。
Tip
To learn how to locate your deployment's connection string, see the Create a Connection String step of the Get Started with the PHP Library tutorial.要了解如何定位部署的连接字符串,请参阅PHP库入门教程的创建连接字符串步骤。
For example, if your connection string is 例如,如果连接字符串是"mongodb+srv://mongodb-example:27017", your connection string assignment resembles the following:"mongodb+srv://mongodb-example:27017",连接字符串分配类似于以下内容:
uri = "mongodb+srv://mongodb-example:27017"Create the Collection创建集合
This example uses a 此示例使用persons collection, which contains documents describing each person's name, date of birth, vocation, and other details. The aggregation selects documents based on whether their field values match specified criteria.persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据文档的字段值是否与指定条件匹配来选择文档。
To create the 要创建persons collection and insert the sample data, add the following code to your application:persons集合并插入示例数据,请将以下代码添加到应用程序中:
person_coll = agg_db["persons"]
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
Create the Template App创建模板应用程序
Before you begin following this aggregation tutorial, you must set up a new Ruby app. You can use this app to connect to a MongoDB deployment, insert sample data into MongoDB, and run the aggregation pipeline.在开始学习本聚合教程之前,您必须设置一个新的Ruby应用程序。您可以使用此应用程序连接到MongoDB部署,将示例数据插入MongoDB,并运行聚合管道。
Tip
To learn how to install the Ruby Driver and connect to MongoDB, see the Get Started with the Ruby Driver guide.要了解如何安装Ruby驱动程序并连接到MongoDB,请参阅Ruby驱动程序入门指南。
To learn more about performing aggregations in the Ruby Driver, see the Aggregation guide.要了解有关在Ruby驱动程序中执行聚合的更多信息,请参阅聚合指南。
After you install the driver, create a file called 安装驱动程序后,创建一个名为agg_tutorial.rb. Paste the following code in this file to create an app template for the aggregation tutorials.agg_tutorial.rb的文件。将以下代码粘贴到此文件中,为聚合教程创建应用程序模板。
Important
In the following code, read the code comments to find the sections of the code that you must modify for the tutorial you are following.在下面的代码中,阅读代码注释,找到您必须为正在学习的教程修改的代码部分。
If you attempt to run the code without making any changes, you will encounter a connection error.如果您尝试在不进行任何更改的情况下运行代码,您将遇到连接错误。
# 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
For every tutorial, you must replace the connection string placeholder with your deployment's connection string.对于每个教程,您必须将连接字符串占位符替换为部署的连接字符串。
Tip
To learn how to locate your deployment's connection string, see the Create a Connection String step of the Ruby Get Started guide.要了解如何定位部署的连接字符串,请参阅Ruby入门指南的创建连接字符串步骤。
For example, if your connection string is 例如,如果连接字符串是"mongodb+srv://mongodb-example:27017", your connection string assignment resembles the following:"mongodb+srv://mongodb-example:27017",连接字符串分配类似于以下内容:
uri = "mongodb+srv://mongodb-example:27017"Create the Collection创建集合
This example uses a 此示例使用persons collection, which contains documents describing each person's name, date of birth, vocation, and other details. The aggregation selects documents based on whether their field values match specified criteria.persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据文档的字段值是否与指定条件匹配来选择文档。
To create the 要创建persons collection and insert the sample data, add the following code to your application: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
Create the Template App创建模板应用程序
Before you begin following this aggregation tutorial, you must set up a new Rust app. You can use this app to connect to a MongoDB deployment, insert sample data into MongoDB, and run the aggregation pipeline.在开始学习本聚合教程之前,您必须设置一个新的Rust应用程序。您可以使用此应用程序连接到MongoDB部署,将示例数据插入MongoDB,并运行聚合管道。
Tip
To learn how to install the driver and connect to MongoDB, see the Rust Driver Quick Start guide.要了解如何安装驱动程序并连接到MongoDB,请参阅Rust驱动程序快速入门指南。
To learn more about performing aggregations in the Rust Driver, see the Aggregation guide.要了解有关在Rust驱动程序中执行聚合的更多信息,请参阅聚合指南。
After you install the driver, create a file called 安装驱动程序后,创建一个名为agg-tutorial.rs. Paste the following code in this file to create an app template for the aggregation tutorials.agg-tutorial.rs的文件。将以下代码粘贴到此文件中,为聚合教程创建应用程序模板。
Important
In the following code, read the code comments to find the sections of the code that you must modify for the tutorial you are following.在下面的代码中,阅读代码注释,找到您必须为正在学习的教程修改的代码部分。
If you attempt to run the code without making any changes, you will encounter a connection error.如果您尝试在不进行任何更改的情况下运行代码,您将遇到连接错误。
use mongodb::{
bson::{doc, Document},
options::ClientOptions,
Client,
};
use futures::stream::TryStreamExt;
use std::error::Error;
// Define structs.
// #[derive(Debug, Serialize, Deserialize)]
// struct MyStruct { ... }
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(())
}
For every tutorial, you must replace the connection string placeholder with your deployment's connection string.对于每个教程,您必须将连接字符串占位符替换为部署的连接字符串。
Tip
To learn how to locate your deployment's connection string, see the Create a Connection String step of the Rust Quick Start guide.要了解如何定位部署的连接字符串,请参阅Rust快速入门指南的创建连接字符串步骤。
For example, if your connection string is 例如,如果连接字符串是"mongodb+srv://mongodb-example:27017", your connection string assignment resembles the following:"mongodb+srv://mongodb-example:27017",连接字符串分配类似于以下内容:
let uri = "mongodb+srv://mongodb-example:27017";Create the Collection创建集合
This example uses a 此示例使用persons collection, which contains documents describing each person's name, date of birth, vocation, and other details. The aggregation selects documents based on whether their field values match specified criteria.persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据文档的字段值是否与指定条件匹配来选择文档。
First, create Rust structs to model the data in the 首先,创建Rust结构体来对persons collection:persons集合中的数据进行建模:
struct Address {
number: i32,
street: String,
city: String,
}
struct Person {
person_id: String,
firstname: String,
lastname: String,
dateofbirth: DateTime,
vocation: String,
address: Address,
}
To create the 要创建persons collection and insert the sample data, add the following code to your application: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?;scala
Create the Template App创建模板应用程序
Before you begin following an aggregation tutorial, you must set up a new Scala app. You can use this app to connect to a MongoDB deployment, insert sample data into MongoDB, and run the aggregation pipeline.在开始学习聚合教程之前,您必须设置一个新的Scala应用程序。您可以使用此应用程序连接到MongoDB部署,将示例数据插入MongoDB,并运行聚合管道。
Tip
To learn how to install the driver and connect to MongoDB, see the Get Started with the Scala Driver guide.要了解如何安装驱动程序并连接到MongoDB,请参阅Scala驱动程序入门指南。
To learn more about performing aggregations in the Scala Driver, see the Aggregation guide.要了解有关在Scala驱动程序中执行聚合的更多信息,请参阅聚合指南。
After you install the driver, create a file called 安装驱动程序后,创建一个名为AggTutorial.scala. Paste the following code in this file to create an app template for the aggregation tutorials.AggTutorial.scala的文件。将以下代码粘贴到此文件中,为聚合教程创建应用程序模板。
Important
In the following code, read the code comments to find the sections of the code that you must modify for the tutorial you are following.在下面的代码中,阅读代码注释,找到您必须为正在学习的教程修改的代码部分。
If you attempt to run the code without making any changes, you will encounter a connection error.如果您尝试在不进行任何更改的情况下运行代码,您将遇到连接错误。
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()
}
}
For every tutorial, you must replace the connection string placeholder with your deployment's connection string.对于每个教程,您必须将连接字符串占位符替换为部署的连接字符串。
Tip
To learn how to locate your deployment's connection string, see the Create a Connection String step of the Scala Driver Get Started guide.要了解如何定位部署的连接字符串,请参阅《Scala驱动程序入门》指南的创建连接字符串步骤。
For example, if your connection string is 例如,如果连接字符串是"mongodb+srv://mongodb-example:27017", your connection string assignment resembles the following:"mongodb+srv://mongodb-example:27017",连接字符串分配类似于以下内容:
val uri = "mongodb+srv://mongodb-example:27017"Create the Collection创建集合
This example uses a 此示例使用persons collection, which contains documents describing each person's name, date of birth, vocation, and other details. The aggregation selects documents based on whether their field values match specified criteria.persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据文档的字段值是否与指定条件匹配来选择文档。
To create the 要创建persons collection and insert the sample data, add the following code to your application: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),
)Steps步骤
The following steps demonstrate how to create and run an aggregation pipeline to filter for a specific subset of documents.以下步骤演示了如何创建和运行聚合管道来筛选特定的文档子集。
MongoDB Shell
Run the aggregation pipeline.运行聚合管道。
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"] }
] )Interpret the aggregation results.解释聚合结果。
The aggregated results contain three documents. The documents represent the three youngest people with the 汇总结果包含三个文档。这些文件代表了三位最年轻的工程师,从最年轻到最年长依次排列。结果省略了vocation of ENGINEER, ordered from youngest to oldest. The results omit the _id and address fields._id和address字段。
{
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'
}C
Add a match stage for people who are engineers.为工程师添加一个匹配阶段。
In your pipeline, create a 在流程中,创建一个$match stage that finds documents in which the value of the vocation field is "ENGINEER":$match阶段,用于查找vocation字段值为"ENGINEER"的文档:
"{", "$match", "{", "vocation", BCON_UTF8("ENGINEER"), "}", "}",Add a sort stage to sort from youngest to oldest.添加一个排序阶段,从最年轻到最年长进行排序。
Next, create a 接下来,创建一个$sort stage that sorts the documents in descending order by the dateofbirth field to list the youngest people first:$sort阶段,按出生日期字段对文档进行降序排序,首先列出最年轻的人:
"{", "$sort", "{", "dateofbirth", BCON_INT32(-1), "}", "}",Add a limit stage to see only three results.添加一个限制阶段,只查看三个结果。
Next, create a 接下来,在管道中创建一个$limit stage to the pipeline to output only the first three documents in the results.$limit阶段,仅输出结果中的前三个文档。
"{", "$limit", BCON_INT32(3), "}",Add an unset stage to remove unneeded fields.添加未设置的阶段以删除不需要的字段。
Finally, create an 最后,创建一个$unset stage. The $unset stage removes unnecessary fields from the result documents:$unset阶段。$unset阶段从结果文档中删除不必要的字段:
"{", "$unset", "[", BCON_UTF8("_id"), BCON_UTF8("address"), "]", "}",
Tip
Use the 如果将具有不同字段的文档添加到集合中,请使用$unset operator instead of $project to avoid modifying the aggregation pipeline if documents with different fields are added to the collection.$unset运算符而不是$project,以避免修改聚合管道。
Run the aggregation pipeline.运行聚合管道。
Add the following code to the end of your application to perform the aggregation on the 将以下代码添加到应用程序的末尾,以对persons collection:persons集合执行聚合:
mongoc_cursor_t *results =
mongoc_collection_aggregate(persons, MONGOC_QUERY_NONE, pipeline, NULL, NULL);
bson_destroy(pipeline);
Ensure that you clean up the collection resources by adding the following line to your cleanup statements:通过在清理语句中添加以下行来确保清理集合资源:
mongoc_collection_destroy(persons);
Finally, run the following commands in your shell to generate and run the executable:最后,在shell中运行以下命令以生成并运行可执行文件:
gcc -o aggc agg-tutorial.c $(pkg-config --libs --cflags libmongoc-1.0)
./aggc
Tip
If you encounter connection errors by running the preceding commands in one call, you can run them separately.如果在一次调用中运行上述命令时遇到连接错误,可以单独运行它们。
Interpret the aggregation results.解释聚合结果。
The aggregated result contains three documents. The documents represent the three youngest people with the vocation of 汇总结果包含三个文档。这些文件代表了三个最年轻的人,他们的职业是"ENGINEER", ordered from youngest to oldest. The results omit the _id and address fields."ENGINEER",从最年轻到最年长依次排列。结果省略了_id和address字段。
{ "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" }C++11
Add a match stage for people who are engineers.为工程师添加一个匹配阶段。
First, add a 首先,添加一个$match stage that finds documents in which the value of the vocation field is "ENGINEER":$match阶段,用于查找vocation字段值为"ENGINEER"的文档:
pipeline.match(bsoncxx::from_json(R"({
"vocation": "ENGINEER"
})"));Add a sort stage to sort from youngest to oldest.添加一个排序阶段,从最年轻到最年长进行排序。
Next, add a 接下来,添加一个$sort stage that sorts the documents in descending order by the dateofbirth field to list the youngest people first:$sort阶段,按dateofbirth字段对文档进行降序排序,以首先列出最年轻的人:
pipeline.sort(bsoncxx::from_json(R"({
"dateofbirth": -1
})"));Add a limit stage to see only three results.添加一个限制阶段,只查看三个结果。
Next, add a 接下来,在管道中添加一个$limit stage to the pipeline to output only the first three documents in the results.$limit阶段,仅输出结果中的前三个文档。
pipeline.limit(3);Add an unset stage to remove unneeded fields.添加未设置的阶段以删除不需要的字段。
Finally, add an 最后,添加一个$unset stage. The $unset stage removes unnecessary fields from the result documents:$unset阶段。$unset阶段从结果文档中删除不必要的字段:
pipeline.append_stage(bsoncxx::from_json(R"({
"$unset": ["_id", "address"]
})"));
Tip
Use the 如果将具有不同字段的文档添加到集合中,请使用$unset operator instead of $project to avoid modifying the aggregation pipeline if documents with different fields are added to the collection.$unset运算符而不是$project,以避免修改聚合管道。
Run the aggregation pipeline.运行聚合管道。
Add the following code to the end of your application to perform the aggregation on the 将以下代码添加到应用程序的末尾,以对persons collection:persons集合执行聚合:
auto cursor = persons.aggregate(pipeline);
Finally, run the following commands in your shell to start your application:最后,在shell中运行以下命令以启动应用程序:
c++ --std=c++17 agg-tutorial.cpp $(pkg-config --cflags --libs libmongocxx) -o ./app.out
./app.outInterpret the aggregation results.解释聚合结果。
The aggregated result contains three documents. The documents represent the three youngest people with the vocation of 汇总结果包含三个文档。这些文件代表了三个最年轻的人,他们的职业是"ENGINEER", ordered from youngest to oldest. The results omit the _id and address fields."ENGINEER",从最年轻到最年长依次排列。结果省略了_id和address字段。
{ "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" }C#
Add a match stage for people who are engineers.为工程师添加一个匹配阶段。
First, start the aggregation on the 首先,在persons collection and chain a $match stage that finds documents in which the value of the Vocation field is "ENGINEER":persons集合上启动聚合,并链接一个$match阶段,该阶段查找Vocation字段值为"ENGINEER"的文档:
var results = persons.Aggregate()
.Match(p => p.Vocation == "ENGINEER")Add a sort stage to sort from youngest to oldest.添加一个排序阶段,从最年轻到最年长进行排序。
Next, add a 接下来,添加一个$sort stage that sorts the documents in descending order by the DateOfBirth field to list the youngest people first:$sort阶段,按DateOfBirth字段降序对文档进行排序,以首先列出最年轻的人:
.Sort(Builders<Person>.Sort.Descending(p => p.DateOfBirth))Add a limit stage to see only three results.添加一个限制阶段,只查看三个结果。
Next, add a 接下来,在管道中添加一个$limit stage to the pipeline to output only the first three documents in the results.$limit阶段,仅输出结果中的前三个文档。
.Limit(3)Add a projection stage to remove unneeded fields.添加投影阶段以删除不需要的字段。
Finally, add a 最后,添加一个$project stage. The $project stage excludes unnecessary fields from the result documents:$project阶段。$project阶段从结果文档中排除了不必要的字段:
.Project(Builders<Person>.Projection
.Exclude(p => p.Address)
.Exclude(p => p.Id)
);Run the aggregation and interpret the results.运行聚合并解释结果。
Finally, run the application in your IDE and inspect the results.最后,在IDE中运行应用程序并检查结果。
The aggregated result contains three documents. The documents represent the three youngest people with the vocation of 汇总结果包含三个文档。这些文件代表了三个最年轻的人,他们的职业是"ENGINEER", ordered from youngest to oldest. The results omit the _id and Address fields."ENGINEER",从最年轻到最年长依次排列。结果省略了_id和Address字段。
{ "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" }Go
Add a match stage for people who are engineers.为工程师添加一个匹配阶段。
First, add a 首先,添加一个$match stage that finds documents in which the value of the vocation field is "ENGINEER":$match阶段,用于查找vocation字段值为"ENGINEER"的文档:
matchStage := bson.D{{Key: "$match", Value: bson.D{{Key: "vocation", Value: "ENGINEER"}}}}Add a sort stage to sort from youngest to oldest.添加一个排序阶段,从最年轻到最年长进行排序。
Next, add a 接下来,添加一个$sort stage that sorts the documents in descending order by the dateofbirth field to list the youngest people first:$sort阶段,按dateofbirth字段对文档进行降序排序,以首先列出最年轻的人:
sortStage := bson.D{{Key: "$sort", Value: bson.D{{Key: "dateofbirth", Value: -1}}}}Add a limit stage to see only three results.添加一个限制阶段,只查看三个结果。
Next, add a 接下来,在管道中添加一个$limit stage to the pipeline to output only the first three documents in the results.$limit阶段,仅输出结果中的前三个文档。
limitStage := bson.D{{Key: "$limit", Value: 3}}Add an unset stage to remove unneeded fields.添加未设置的阶段以删除不需要的字段。
Finally, add an 最后,添加一个$unset stage. The $unset stage removes unnecessary fields from the result documents:$unset阶段。$unset阶段从结果文档中删除不必要的字段:
unsetStage := bson.D{{Key: "$unset", Value: bson.A{"_id", "address"}}}
Tip
Use the 如果将具有不同字段的文档添加到集合中,请使用$unset operator instead of $project to avoid modifying the aggregation pipeline if documents with different fields are added to the collection.$unset运算符而不是$project,以避免修改聚合管道。
Run the aggregation pipeline.运行聚合管道。
Add the following code to the end of your application to perform the aggregation on the 将以下代码添加到应用程序的末尾,以对persons collection:persons集合执行聚合:
pipeline := mongo.Pipeline{matchStage, sortStage, limitStage, unsetStage}
cursor, err := persons.Aggregate(ctx, pipeline)
Finally, run the application and inspect the results.最后,运行应用程序并检查结果。
Interpret the aggregation results.解释聚合结果。
The aggregated result contains three documents. The documents represent the three youngest people with the vocation of 汇总结果包含三个文档。这些文件代表了三个最年轻的人,他们的职业是"ENGINEER", ordered from youngest to oldest. The results omit the _id and address fields."ENGINEER",从最年轻到最年长依次排列。结果省略了_id和address字段。
{"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"}Java(Sync)
Add a match stage for people who are engineers.为工程师添加一个匹配阶段。
First, add a 首先,添加一个$match stage that finds documents in which the value of the vocation field is "ENGINEER":$match阶段,用于查找vocation字段值为"ENGINEER"的文档:
pipeline.add(Aggregates.match(Filters.eq("vocation", "ENGINEER")));Add a sort stage to sort from youngest to oldest.添加一个排序阶段,从最年轻到最年长进行排序。
Next, add a 接下来,添加一个$sort stage that sorts the documents in descending order by the dateofbirth field to list the youngest people first:$sort阶段,按dateofbirth字段对文档进行降序排序,以首先列出最年轻的人:
pipeline.add(Aggregates.sort(Sorts.descending("dateofbirth")));Add a limit stage to see only three results.添加一个限制阶段,只查看三个结果。
Next, add a 接下来,在管道中添加一个$limit stage to the pipeline to output only the first three documents in the results.$limit阶段,仅输出结果中的前三个文档。
pipeline.add(Aggregates.limit(3));Add an unset stage to remove unneeded fields.添加未设置的阶段以删除不需要的字段。
Finally, add an 最后,添加一个$unset stage. The $unset stage removes unnecessary fields from the result documents:$unset阶段。$unset阶段从结果文档中删除不必要的字段:
pipeline.add(Aggregates.unset("_id", "address"));
Tip
Use the 如果将具有不同字段的文档添加到集合中,请使用$unset operator instead of $project to avoid modifying the aggregation pipeline if documents with different fields are added to the collection.$unset运算符而不是$project,以避免修改聚合管道。
Run the aggregation pipeline.运行聚合管道。
Add the following code to the end of your application to perform the aggregation on the 将以下代码添加到应用程序的末尾,以对persons collection:persons集合执行聚合:
AggregateIterable<Document> aggregationResult = persons.aggregate(pipeline);
Finally, run the application in your IDE.最后,在IDE中运行应用程序。
Interpret the aggregation results.解释聚合结果。
The aggregated result contains three documents. The documents represent the three youngest people with the vocation of 汇总结果包含三个文档。这些文件代表了三个最年轻的人,他们的职业是"ENGINEER", ordered from youngest to oldest. The results omit the _id and address fields."ENGINEER",从最年轻到最年长依次排列。结果省略了_id和address字段。
{"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"}Kotlin(Coroutine)
Add a match stage for people who are engineers.为工程师添加一个匹配阶段。
First, add a 首先,添加一个$match stage that finds documents in which the value of the vocation field is "ENGINEER":$match阶段,用于查找vocation字段值为"ENGINEER"的文档:
pipeline.add(Aggregates.match(Filters.eq(Person::vocation.name, "ENGINEER")))Add a sort stage to sort from youngest to oldest.添加一个排序阶段,从最年轻到最年长进行排序。
Next, add a 接下来,添加一个$sort stage that sorts the documents in descending order by the dateOfBirth field to list the youngest people first:$sort阶段,按dateOfBirth字段降序对文档进行排序,以首先列出最年轻的人:
pipeline.add(Aggregates.sort(Sorts.descending(Person::dateOfBirth.name)))Add a limit stage to see only three results.添加一个限制阶段,只查看三个结果。
Next, add a 接下来,在管道中添加一个$limit stage to the pipeline to output only the first three documents in the results.$limit阶段,仅输出结果中的前三个文档。
pipeline.add(Aggregates.limit(3))Add an unset stage to remove unneeded fields.添加未设置的阶段以删除不需要的字段。
Finally, add an 最后,添加一个$unset stage. The $unset stage removes unnecessary fields from the result documents:$unset阶段。$unset阶段从结果文档中删除不必要的字段:
pipeline.add(Aggregates.unset("_id", Person::address.name))
Tip
Use the 如果将具有不同字段的文档添加到集合中,请使用$unset operator instead of $project to avoid modifying the aggregation pipeline if documents with different fields are added to the collection.$unset运算符而不是$project,以避免修改聚合管道。
Run the aggregation pipeline.运行聚合管道。
Add the following code to the end of your application to perform the aggregation on the 将以下代码添加到应用程序的末尾,以对persons collection:persons集合执行聚合:
val aggregationResult = persons.aggregate<Document>(pipeline)
Finally, run the application in your IDE.最后,在IDE中运行应用程序。
Interpret the aggregation results.解释聚合结果。
The aggregated result contains three documents. The documents represent the three youngest people with the vocation of 汇总结果包含三个文档。这些文件代表了三个最年轻的人,他们的职业是"ENGINEER", ordered from youngest to oldest. The results omit the _id and address fields."ENGINEER",从最年轻到最年长依次排列。结果省略了_id和address字段。
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}}Node.js
Add a match stage for people who are engineers.为工程师添加一个匹配阶段。
First, add a 首先,添加一个$match stage that finds documents in which the value of the vocation field is "ENGINEER":$match阶段,用于查找vocation字段值为"ENGINEER"的文档:
pipeline.push({
$match: {
vocation: 'ENGINEER',
},
});Add a sort stage to sort from youngest to oldest.添加一个排序阶段,从最年轻到最年长进行排序。
Next, add a 接下来,添加一个$sort stage that sorts the documents in descending order by the dateofbirth field to list the youngest people first:$sort阶段,按dateofbirth字段对文档进行降序排序,以首先列出最年轻的人:
pipeline.push({
$sort: {
dateofbirth: -1,
},
});Add a limit stage to see only three results.添加一个限制阶段,只查看三个结果。
Next, add a 接下来,在管道中添加一个$limit stage to the pipeline to output only the first three documents in the results.$limit阶段,仅输出结果中的前三个文档。
pipeline.push({
$limit: 3,
});Add an unset stage to remove unneeded fields.添加未设置的阶段以删除不需要的字段。
Finally, add an 最后,添加一个$unset stage. The $unset stage removes unnecessary fields from the result documents:$unset阶段。$unset阶段从结果文档中删除不必要的字段:
pipeline.push({
$unset: ['_id', 'address'],
});
Tip
Use the 如果将具有不同字段的文档添加到集合中,请使用$unset operator instead of $project to avoid modifying the aggregation pipeline if documents with different fields are added to the collection.$unset运算符而不是$project,以避免修改聚合管道。
Run the aggregation pipeline.运行聚合管道。
Add the following code to the end of your application to perform the aggregation on the 将以下代码添加到应用程序的末尾,以对persons collection:persons集合执行聚合:
const aggregationResult = await persons.aggregate(pipeline);
Finally, execute the code in the file using your IDE or the command line.最后,使用IDE或命令行执行文件中的代码。
Interpret the aggregation results.解释聚合结果。
The aggregated result contains three documents. The documents represent the three youngest people with the vocation of 汇总结果包含三个文档。这些文件代表了三个最年轻的人,他们的职业是"ENGINEER", ordered from youngest to oldest. The results omit the _id and address fields."ENGINEER",从最年轻到最年长依次排列。结果省略了_id和address字段。
{
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'
}PHP
Add a match stage for people who are engineers.为工程师添加一个匹配阶段。
In your 在Pipeline instance, create a $match stage that finds documents in which the value of the vocation field is "ENGINEER":Pipeline实例中,创建一个$match阶段,用于查找vocation字段值为"ENGINEER"的文档:
Stage::match(vocation: 'ENGINEER'),Add a sort stage to sort from youngest to oldest.添加一个排序阶段,从最年轻到最年长进行排序。
Next, create a 接下来,创建一个$sort stage that sorts the documents in descending order by the dateofbirth field to list the youngest people first:$sort阶段,按dateofbirth字段对文档进行降序排序,首先列出最年轻的人:
Stage::sort(dateofbirth: Sort::Desc),Add a limit stage to see only three results.添加一个限制阶段,只查看三个结果。
Next, create a 接下来,在管道中创建一个$limit stage to the pipeline to output only the first three documents in the results.$limit阶段,仅输出结果中的前三个文档。
Stage::limit(3),Add an unset stage to remove unneeded fields.添加未设置的阶段以删除不需要的字段。
Finally, create an 最后,创建一个$unset stage. The $unset stage removes unnecessary fields from the result documents:$unset阶段。$unset阶段从结果文档中删除不必要的字段:
Stage::unset('_id', 'address')
Tip
Use the 如果将具有不同字段的文档添加到集合中,请使用$unset operator instead of $project to avoid modifying the aggregation pipeline if documents with different fields are added to the collection.$unset运算符而不是$project,以避免修改聚合管道。
Run the aggregation pipeline.运行聚合管道。
Add the following code to the end of your application to perform the aggregation on the 将以下代码添加到应用程序的末尾,以对persons collection:persons集合执行聚合:
$cursor = $persons->aggregate($pipeline);
Finally, run the following command in your shell to start your application:最后,在shell中运行以下命令以启动应用程序:
php agg_tutorial.phpInterpret the aggregation results.解释聚合结果。
The aggregated result contains three documents. The documents represent the three youngest people with the vocation of 汇总结果包含三个文档。这些文件代表了三个最年轻的人,他们的职业是"ENGINEER", ordered from youngest to oldest. The results omit the _id and address fields."ENGINEER",从最年轻到最年长依次排列。结果省略了_id和address字段。
{
"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"
}Python
Add a match stage for people who are engineers.为工程师添加一个匹配阶段。
In your 在Pipeline实例中,创建一个Pipeline instance, create a $match stage that finds documents in which the value of the vocation field is "ENGINEER":$match阶段,用于查找vocation字段值为"ENGINEER"的文档:
pipeline.append({"$match": {"vocation": "ENGINEER"}})Add a sort stage to sort from youngest to oldest.添加一个排序阶段,从最年轻到最年长进行排序。
Next, create a 接下来,创建一个$sort stage that sorts the documents in descending order by the dateofbirth field to list the youngest people first:$sort阶段,按dateofbirth字段对文档进行降序排序,首先列出最年轻的人:
pipeline.append({"$sort": {"dateofbirth": -1}})Add a limit stage to see only three results.添加一个限制阶段,只查看三个结果。
Next, create a 接下来,在管道中创建一个$limit stage to the pipeline to output only the first three documents in the results.$limit阶段,仅输出结果中的前三个文档。
pipeline.append({"$limit": 3})Add an unset stage to remove unneeded fields.添加未设置的阶段以删除不需要的字段。
Finally, create an 最后,创建一个$unset stage. The $unset stage removes unnecessary fields from the result documents:$unset阶段。$unset阶段从结果文档中删除不必要的字段:
pipeline.append({"$unset": ["_id", "address"]})
Tip
Use the 如果将具有不同字段的文档添加到集合中,请使用$unset operator instead of $project to avoid modifying the aggregation pipeline if documents with different fields are added to the collection.$unset运算符而不是$project,以避免修改聚合管道。
Run the aggregation pipeline.运行聚合管道。
Add the following code to the end of your application to perform the aggregation on the 将以下代码添加到应用程序的末尾,以对persons collection:persons集合执行聚合:
aggregation_result = person_coll.aggregate(pipeline)
Finally, run the following command in your shell to start your application:最后,在shell中运行以下命令以启动应用程序:
python3 agg_tutorial.pyInterpret the aggregation results.解释聚合结果。
The aggregated result contains three documents. The documents represent the three youngest people with the vocation of 汇总结果包含三个文档。这些文件代表了三个最年轻的人,他们的职业是"ENGINEER", ordered from youngest to oldest. The results omit the _id and address fields."ENGINEER",从最年轻到最年长依次排列。结果省略了_id和address字段。
{'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'}Ruby
Add a match stage for people who are engineers.为工程师添加一个匹配阶段。
First, add a 首先,添加一个$match stage that finds documents in which the value of the vocation field is "ENGINEER":$match阶段,用于查找vocation字段值为"ENGINEER"的文档:
{ "$match": { "vocation": "ENGINEER" } },Add a sort stage to sort from youngest to oldest.添加一个排序阶段,从最年轻到最年长进行排序。
Next, add a 接下来,添加一个$sort stage that sorts the documents in descending order by the dateofbirth field to list the youngest people first:$sort阶段,按dateofbirth字段对文档进行降序排序,以首先列出最年轻的人:
{ "$sort": { "dateofbirth": -1 } },Add a limit stage to see only three results.添加一个限制阶段,只查看三个结果。
Next, add a 接下来,在管道中添加一个$limit stage to the pipeline to output only the first three documents in the results.$limit阶段,仅输出结果中的前三个文档。
{ "$limit": 3 },Add an unset stage to remove unneeded fields.添加未设置的阶段以删除不需要的字段。
Finally, add an 最后,添加一个$unset stage. The $unset stage removes unnecessary fields from the result documents:$unset阶段。$unset阶段从结果文档中删除不必要的字段:
{ "$unset": ["_id", "address"] },
Tip
Use the 如果将具有不同字段的文档添加到集合中,请使用$unset operator instead of $project to avoid modifying the aggregation pipeline if documents with different fields are added to the collection.$unset运算符而不是$project,以避免修改聚合管道。
Run the aggregation pipeline.运行聚合管道。
Add the following code to the end of your application to perform the aggregation on the 将以下代码添加到应用程序的末尾,以对persons collection:persons集合执行聚合:
aggregation_result = persons.aggregate(pipeline)
Finally, run the following command in your shell to start your application:最后,在shell中运行以下命令以启动应用程序:
node agg_tutorial.rbInterpret the aggregation results.解释聚合结果。
The aggregated result contains three documents. The documents represent the three youngest people with the vocation of 汇总结果包含三个文档。这些文件代表了三个最年轻的人,他们的职业是“工程师”,从最年轻到最年长依次排列。结果省略了"ENGINEER", ordered from youngest to oldest. The results omit the _id and address fields._id和address字段。
{"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"}Rust
Add a match stage for people who are engineers.为工程师添加一个匹配阶段。
First, add a 首先,添加一个$match stage that finds documents in which the value of the vocation field is "ENGINEER":$match阶段,用于查找vocation(职业)字段值为"ENGINEER"的文档:
pipeline.push(doc! { "$match": { "vocation": "ENGINEER" } });Add a sort stage to sort from youngest to oldest.添加一个排序阶段,从最年轻到最年长进行排序。
Next, add a 接下来,添加一个$sort stage that sorts the documents in descending order by the dateofbirth field to list the youngest people first:$sort阶段,按出生日期字段对文档进行降序排序,以首先列出最年轻的人:
pipeline.push(doc! { "$sort": { "dateofbirth": -1 } });Add a limit stage to see only three results.添加一个限制阶段,只查看三个结果。
Next, add a 接下来,在管道中添加一个$limit stage to the pipeline to output only the first three documents in the results.$limit阶段,仅输出结果中的前三个文档。
pipeline.push(doc! { "$limit": 3 });Add an unset stage to remove unneeded fields.添加未设置的阶段以删除不需要的字段。
Finally, add an 最后,添加一个$unset stage. The $unset stage removes unnecessary fields from the result documents:$unset阶段。$unset阶段从结果文档中删除不必要的字段:
pipeline.push(doc! { "$unset": ["_id", "address"] });
Tip
Use the 如果将具有不同字段的文档添加到集合中,请使用$unset operator instead of $project to avoid modifying the aggregation pipeline if documents with different fields are added to the collection.$unset运算符而不是$project,以避免修改聚合管道。
Run the aggregation pipeline.运行聚合管道。
Add the following code to the end of your application to perform the aggregation on the 将以下代码添加到应用程序的末尾,以对persons collection:persons集合执行聚合:
let mut cursor = persons.aggregate(pipeline).await?;
Finally, run the following command in your shell to start your application:最后,在shell中运行以下命令以启动应用程序:
cargo runInterpret the aggregation results.解释聚合结果。
The aggregated result contains three documents. The documents represent the three youngest people with the vocation of 汇总结果包含三个文档。这些文件代表了三个最年轻的人,他们的职业是"ENGINEER", ordered from youngest to oldest. The results omit the _id and address fields."ENGINEER",从最年轻到最年长依次排列。结果省略了_id和address字段。
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")})scala
Add a match stage for people who are engineers.为工程师添加一个匹配阶段。
First, add a 首先,添加一个$match stage that finds documents in which the value of the vocation field is "ENGINEER":$match阶段,用于查找vocation字段值为"ENGINEER"的文档:
Aggregates.filter(Filters.equal("vocation", "ENGINEER")),Add a sort stage to sort from youngest to oldest.添加一个排序阶段,从最年轻到最年长进行排序。
Next, add a 接下来,添加一个$sort stage that sorts the documents in descending order by the dateofbirth field to list the youngest people first:$sort阶段,按dateofbirth字段对文档进行降序排序,以首先列出最年轻的人:
Aggregates.sort(Sorts.descending("dateofbirth")),Add a limit stage to see only three results.添加一个限制阶段,只查看三个结果。
Next, add a 接下来,在管道中添加一个$limit stage to the pipeline to output only the first three documents in the results.$limit阶段,仅输出结果中的前三个文档。
Aggregates.limit(3),Add an unset stage to remove unneeded fields.添加未设置的阶段以删除不需要的字段。
Finally, add an 最后,添加一个$unset stage. The $unset stage removes unnecessary fields from the result documents:$unset阶段。$unset阶段从结果文档中删除不必要的字段:
Aggregates.unset("_id", "address")
Tip
Use the 如果将具有不同字段的文档添加到集合中,请使用$unset operator instead of $project to avoid modifying the aggregation pipeline if documents with different fields are added to the collection.$unset运算符而不是$project,以避免修改聚合管道。
Run the aggregation pipeline.运行聚合管道。
Add the following code to the end of your application to perform the aggregation on the 将以下代码添加到应用程序的末尾,以对persons collection:persons集合执行聚合:
persons.aggregate(pipeline)
.subscribe((doc: Document) => println(doc.toJson()),
(e: Throwable) => println(s"Error: $e"))
Finally, run the application in your IDE.最后,在IDE中运行应用程序。
Interpret the aggregation results.解释聚合结果。
The aggregated result contains three documents. The documents represent the three youngest people with the vocation of 汇总结果包含三个文档。这些文件代表了三个最年轻的人,他们的职业是"ENGINEER", ordered from youngest to oldest. The results omit the _id and address fields."ENGINEER",从最年轻到最年长依次排列。结果省略了_id和address字段。
{"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"}