Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs 菜单
Docs 主页
/
数据库手册
/ / /

过滤数据

本教程说明了如何构建聚合管道、对集合执行聚合以及使用您选择的语言显示结果。

本教程演示如何查询集合中的特定文档子集。

聚合管道执行以下操作:

  • 根据字段值匹配文档子集

  • 格式结果文档


➤ 使用右上角的 Select your 语言)下拉菜单设立以下示例的语言,或选择MongoDB Shell。


此示例使用 persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据字段值是否与指定条件匹配来选择文档。

要创建 persons集合,请使用 insertMany() 方法:

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

在开始学习本聚合教程之前,您必须设立一个新的C应用。您可以使用此应用连接到MongoDB 部署,将示例数据插入MongoDB,然后运行聚合管道。

提示

要学习;了解如何安装驾驶员和连接到MongoDB,请参阅 C驱动程序入门指南。

要学习;了解有关在C驱动程序中执行聚合的更多信息,请参阅聚合指南。

安装驾驶员后,创建一个名为 agg-tutorial.c 的文件。将以下代码粘贴到此文件中,为聚合教程创建应用模板。

重要

在以下代码中,阅读代码注释,找到必须根据教程修改的代码部分。

如果您尝试在不进行任何更改的情况下运行代码,则会遇到连接错误。

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

对于每个教程,您必须用部署的连接字符串替换连接字符串占位符。

提示

要学习;了解如何找到部署的连接字符串,请参阅C语言入门指南中的创建连接字符串步骤。

例如,如果连接字符串为 "mongodb+srv://mongodb-example:27017",则其赋值应如下所示:

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

此示例使用 persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据字段值是否与指定条件匹配来选择文档。

要创建 persons集合并插入示例数据,请将以下代码添加到您的应用程序中:

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

在开始学习聚合教程之前,您必须设立一个新的C++应用。您可以使用此应用连接到MongoDB 部署,将示例数据插入MongoDB,然后运行聚合管道。

提示

要学习;了解如何安装驾驶员并连接到MongoDB,请参阅C++入门教程

要学习;了解有关使用C++驾驶员的更多信息,请参阅API文档。

要学习;了解有关在C++驱动程序中执行聚合的更多信息,请参阅聚合指南。

安装驾驶员后,创建一个名为 agg-tutorial.cpp 的文件。将以下代码粘贴到此文件中,为聚合教程创建应用模板。

重要

在以下代码中,阅读代码注释,找到必须根据教程修改的代码部分。

如果您尝试在不进行任何更改的情况下运行代码,则会遇到连接错误。

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

对于每个教程,您必须用部署的连接字符串替换连接字符串占位符。

提示

要学习;了解如何找到部署的连接字符串,请参阅C++入门教程中的创建连接字符串步骤。

例如,如果连接字符串为 "mongodb+srv://mongodb-example:27017",则其赋值应如下所示:

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

此示例使用 persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据字段值是否与指定条件匹配来选择文档。

要创建 persons集合并插入示例数据,请将以下代码添加到您的应用程序中:

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

在开始学习此聚合教程之前,必须设立一个新的C#/ .NET应用。您可以使用此应用连接到MongoDB 部署,将示例数据插入MongoDB,然后运行聚合管道。

提示

要学习;了解如何安装驾驶员和连接到MongoDB,请参阅C#/.NET驱动程序快速入门指南。

要学习;了解有关在C#/. .NET驱动程序中执行聚合的更多信息,请参阅聚合指南。

安装驾驶员后,将以下代码粘贴到 Program.cs文件中,为聚合教程创建应用模板。

重要

在以下代码中,阅读代码注释,找到必须根据教程修改的代码部分。

如果您尝试在不进行任何更改的情况下运行代码,则会遇到连接错误。

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

对于每个教程,您必须用部署的连接字符串替换连接字符串占位符。

提示

要学习;了解如何找到部署的连接字符串,请参阅C#快速入门指南中的在Atlas中设置免费层级集群步骤。

例如,如果连接字符串为 "mongodb+srv://mongodb-example:27017",则其赋值应如下所示:

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

此示例使用 persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据字段值是否与指定条件匹配来选择文档。

首先,创建C#类来对 persons集合中的数据进行建模:

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

要创建 persons集合并插入示例数据,请将以下代码添加到您的应用程序中:

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

在开始学习此聚合教程之前,您必须设立一个新的Go应用。您可以使用此应用连接到MongoDB 部署,将示例数据插入MongoDB,然后运行聚合管道。

提示

要学习;了解如何安装驾驶员并连接到MongoDB,请参阅Go驱动程序快速入门指南。

要学习;了解有关在Go驱动程序中执行聚合的更多信息,请参阅聚合指南。

安装驾驶员后,创建一个名为 agg_tutorial.go 的文件。将以下代码粘贴到此文件中,为聚合教程创建应用模板。

重要

在以下代码中,阅读代码注释,找到必须根据教程修改的代码部分。

如果您尝试在不进行任何更改的情况下运行代码,则会遇到连接错误。

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

对于每个教程,您必须用部署的连接字符串替换连接字符串占位符。

提示

要学习;了解如何找到部署的连接字符串,请参阅Go快速入门指南中的创建MongoDB集群步骤。

例如,如果连接字符串为 "mongodb+srv://mongodb-example:27017",则其赋值应如下所示:

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

此示例使用 persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据字段值是否与指定条件匹配来选择文档。

首先,创建Go结构体以对 persons集合中的数据进行建模:

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

要创建 persons集合并插入示例数据,请将以下代码添加到您的应用程序中:

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

在开始学习聚合教程之前,您必须设立一个新的Java应用。您可以使用此应用连接到MongoDB 部署,将示例数据插入MongoDB,然后运行聚合管道。

提示

要学习;了解如何安装驾驶员并连接到MongoDB,请参阅Java驱动程序入门指南。

要学习;了解有关在Java Sync 驱动程序中执行聚合的更多信息,请参阅聚合指南。

安装驾驶员后,创建一个名为 AggTutorial.java 的文件。将以下代码粘贴到此文件中,为聚合教程创建应用模板。

重要

在以下代码中,阅读代码注释,找到必须根据教程修改的代码部分。

如果您尝试在不进行任何更改的情况下运行代码,则会遇到连接错误。

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

对于每个教程,您必须用部署的连接字符串替换连接字符串占位符。

提示

要学习;了解如何找到部署的连接字符串,请参阅Java Sync 快速入门指南的创建连接字符串步骤。

例如,如果连接字符串为 "mongodb+srv://mongodb-example:27017",则其赋值应如下所示:

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

此示例使用 persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据字段值是否与指定条件匹配来选择文档。

要创建 persons集合并插入示例数据,请将以下代码添加到您的应用程序中:

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

在开始学习聚合教程之前,您必须设立一个新的Kotlin应用。您可以使用此应用连接到MongoDB 部署,将示例数据插入MongoDB,然后运行聚合管道。

提示

要学习;了解如何安装驾驶员并连接到MongoDB,请参阅Kotlin驱动程序快速入门指南。

要学习;了解有关在Kotlin驱动程序中执行聚合的更多信息,请参阅聚合指南。

除驾驶员外,您还必须将以下依赖项添加到 build.gradle.kts文件中并重新加载项目:

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

安装驾驶员后,创建一个名为 AggTutorial.kt 的文件。将以下代码粘贴到此文件中,为聚合教程创建应用模板。

重要

在以下代码中,阅读代码注释,找到必须根据教程修改的代码部分。

如果您尝试在不进行任何更改的情况下运行代码,则会遇到连接错误。

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

对于每个教程,您必须用部署的连接字符串替换连接字符串占位符。

提示

要学习;了解如何找到部署的连接字符串,请参阅Kotlin驱动程序快速入门指南中的连接到集群步骤。

例如,如果连接字符串为 "mongodb+srv://mongodb-example:27017",则其赋值应如下所示:

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

此示例使用 persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据字段值是否与指定条件匹配来选择文档。

首先,创建Kotlin数据类以对 persons集合中的数据进行建模:

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

要创建 persons集合并插入示例数据,请将以下代码添加到您的应用程序中:

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

在开始学习此聚合教程之前,您必须设立一个新的 Node.js应用。您可以使用此应用连接到MongoDB 部署,将示例数据插入MongoDB,然后运行聚合管道。

提示

要学习;了解如何安装驾驶员和连接到MongoDB,请参阅 Node.js驱动程序快速入门指南。

要学习;了解有关在 Node.js驱动程序中执行聚合的更多信息,请参阅聚合指南。

安装驾驶员后,创建一个名为 agg_tutorial.js 的文件。将以下代码粘贴到此文件中,为聚合教程创建应用模板。

重要

在以下代码中,阅读代码注释,找到必须根据教程修改的代码部分。

如果您尝试在不进行任何更改的情况下运行代码,则会遇到连接错误。

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

对于每个教程,您必须用部署的连接字符串替换连接字符串占位符。

提示

要学习;了解如何查找部署的连接字符串,请参阅 Node.js 快速入门指南的创建连接字符串步骤。

例如,如果连接字符串为 "mongodb+srv://mongodb-example:27017",则其赋值应如下所示:

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

此示例使用 persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据字段值是否与指定条件匹配来选择文档。

要创建 persons集合并插入示例数据,请将以下代码添加到您的应用程序中:

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

在开始学习此聚合教程之前,您必须设立一个新的PHP应用。您可以使用此应用连接到MongoDB 部署,将示例数据插入MongoDB,然后运行聚合管道。

提示

要学习;了解如何安装PHP库并连接到MongoDB,请参阅PHP库入门教程。

要学习;了解有关在PHP库中执行聚合的更多信息,请参阅 聚合指南。

安装该库后,创建一个名为 agg_tutorial.php 的文件。将以下代码粘贴到此文件中,为聚合教程创建应用模板。

重要

在以下代码中,阅读代码注释,找到必须根据教程修改的代码部分。

如果您尝试在不进行任何更改的情况下运行代码,则会遇到连接错误。

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

对于每个教程,您必须用部署的连接字符串替换连接字符串占位符。

提示

要学习;了解如何找到部署的连接字符串,请参阅PHP库入门教程中的创建连接字符串步骤。

例如,如果连接字符串为 "mongodb+srv://mongodb-example:27017",则其赋值应如下所示:

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

此示例使用 persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据字段值是否与指定条件匹配来选择文档。

要创建 persons集合并插入示例数据,请将以下代码添加到您的应用程序中:

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

在开始学习本聚合教程之前,您必须设立一个新的Python应用。您可以使用此应用连接到MongoDB 部署,将示例数据插入MongoDB,然后运行聚合管道。

提示

要学习;了解如何安装PyMongo并连接到MongoDB,请参阅PyMongo入门教程

要学习;了解有关在PyMongo中执行聚合的更多信息,请参阅聚合指南。

安装该库后,创建一个名为 agg_tutorial.py 的文件。将以下代码粘贴到此文件中,为聚合教程创建应用模板。

重要

在以下代码中,阅读代码注释,找到必须根据教程修改的代码部分。

如果您尝试在不进行任何更改的情况下运行代码,则会遇到连接错误。

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

对于每个教程,您必须用部署的连接字符串替换连接字符串占位符。

提示

要学习;了解如何找到部署的连接字符串,请参阅PHP库入门教程中的创建连接字符串步骤。

例如,如果连接字符串为 "mongodb+srv://mongodb-example:27017",则其赋值应如下所示:

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

此示例使用 persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据字段值是否与指定条件匹配来选择文档。

要创建 persons集合并插入示例数据,请将以下代码添加到您的应用程序中:

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

在开始学习此聚合教程之前,您必须设立一个新的Ruby应用。您可以使用此应用连接到MongoDB 部署,将示例数据插入MongoDB,然后运行聚合管道。

提示

要学习;了解如何安装Ruby驱动程序并连接到MongoDB,请参阅Ruby驱动程序入门指南。

要学习;了解有关在Ruby驱动程序中执行聚合的更多信息,请参阅聚合指南。

安装驾驶员后,创建一个名为 agg_tutorial.rb 的文件。将以下代码粘贴到此文件中,为聚合教程创建应用模板。

重要

在以下代码中,阅读代码注释,找到必须根据教程修改的代码部分。

如果您尝试在不进行任何更改的情况下运行代码,则会遇到连接错误。

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

对于每个教程,您必须用部署的连接字符串替换连接字符串占位符。

提示

要学习;了解如何查找部署的连接字符串,请参阅Ruby入门指南的创建连接字符串步骤。

例如,如果连接字符串为 "mongodb+srv://mongodb-example:27017",则其赋值应如下所示:

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

此示例使用 persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据字段值是否与指定条件匹配来选择文档。

要创建 persons集合并插入示例数据,请将以下代码添加到您的应用程序中:

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

在开始学习本聚合教程之前,您必须设立一个新的Rust应用。您可以使用此应用连接到MongoDB 部署,将示例数据插入MongoDB,然后运行聚合管道。

提示

要学习;了解如何安装驾驶员并连接到MongoDB,请参阅Rust驱动程序快速入门指南。

要学习;了解有关在Rust驱动程序中执行聚合的更多信息,请参阅聚合指南。

安装驾驶员后,创建一个名为 agg-tutorial.rs 的文件。将以下代码粘贴到此文件中,为聚合教程创建应用模板。

重要

在以下代码中,阅读代码注释,找到必须根据教程修改的代码部分。

如果您尝试在不进行任何更改的情况下运行代码,则会遇到连接错误。

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

对于每个教程,您必须用部署的连接字符串替换连接字符串占位符。

提示

要学习;了解如何找到部署的连接字符串,请参阅Rust快速入门指南的创建连接字符串步骤。

例如,如果连接字符串为 "mongodb+srv://mongodb-example:27017",则其赋值应如下所示:

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

此示例使用 persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据字段值是否与指定条件匹配来选择文档。

首先,创建Rust结构体以对 persons集合中的数据进行建模:

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

要创建 persons集合并插入示例数据,请将以下代码添加到您的应用程序中:

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

在开始学习聚合教程之前,您必须设立一个新的Scala应用。您可以使用此应用连接到MongoDB 部署,将示例数据插入MongoDB,然后运行聚合管道。

提示

要学习;了解如何安装驾驶员并连接到MongoDB,请参阅Scala驱动程序指南

要学习;了解有关在Scala驱动程序中执行聚合的更多信息,请参阅聚合指南。

安装驾驶员后,创建一个名为 AggTutorial.scala 的文件。将以下代码粘贴到此文件中,为聚合教程创建应用模板。

重要

在以下代码中,阅读代码注释,找到必须根据教程修改的代码部分。

如果您尝试在不进行任何更改的情况下运行代码,则会遇到连接错误。

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

对于每个教程,您必须用部署的连接字符串替换连接字符串占位符。

提示

要学习;了解如何找到部署的连接字符串,请参阅Scala驱动程序入门指南中的创建连接字符串步骤。

例如,如果连接字符串为 "mongodb+srv://mongodb-example:27017",则其赋值应如下所示:

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

此示例使用 persons集合,其中包含描述每个人的姓名、出生日期、职业和其他详细信息的文档。聚合根据字段值是否与指定条件匹配来选择文档。

要创建 persons集合并插入示例数据,请将以下代码添加到您的应用程序中:

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

以下步骤演示如何创建和运行聚合管道以过滤特定的文档子集。

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

聚合结果包含三个文档。这些文档代表 vocationENGINEER 的三个最年轻的人,按从最小到最大的顺序排列。结果省略了 _idaddress 字段。

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

在您的管道中,创建一个 $match 阶段,用于查找 vocation字段的值为 "ENGINEER" 的文档:

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

接下来,创建一个 $sort 阶段,按 dateofbirth字段降序对文档进行排序,从而首先列出最年轻的人:

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

接下来,为管道创建一个 $limit 阶段,以仅输出结果中的前三个文档。

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

最后,创建一个$unset阶段。$unset 阶段会从结果文档中删除不必要的字段:

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

提示

如果将具有不同字段的文档添加到集合中,请使用 $unset 操作符而不是 $project 来避免修改聚合管道。

5

将以下代码添加到应用程序末尾,以对personscollection执行聚合:

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

通过将以下行添加到清理语句中,确保清理集合资源:

mongoc_collection_destroy(persons);

最后,在Shell中运行以下命令,生成并运行可执行文件:

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

提示

如果在一次调用中运行上述命令时遇到连接错误,可以单独运行。

6

聚合结果包含三个文档。这些文档代表了职业为"ENGINEER"的三个最年轻的人,按从幼到长的顺序排列。结果省略了 _idaddress 字段。

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

首先,添加一个 $match 阶段,用于查找 vocation字段的值为 "ENGINEER" 的文档:

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

接下来,添加一个 $sort 阶段,按 dateofbirth字段对文档进行降序排序,从而首先列出最年轻的人员:

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

接下来,向管道添加一个 $limit 阶段,以仅输出结果中的前三个文档。

pipeline.limit(3);
4

最后,添加一个$unset阶段。$unset 阶段会从结果文档中删除不必要的字段:

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

提示

如果将具有不同字段的文档添加到集合中,请使用 $unset 操作符而不是 $project 来避免修改聚合管道。

5

将以下代码添加到应用程序末尾,以对personscollection执行聚合:

auto cursor = persons.aggregate(pipeline);

最后,在Shell中运行以下命令来启动应用程序:

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

聚合结果包含三个文档。这些文档代表了职业为"ENGINEER"的三个最年轻的人,按从幼到长的顺序排列。结果省略了 _idaddress 字段。

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

首先,在 persons集合上启动聚合,并链接一个 $match 阶段,用于查找 Vocation字段的值为 "ENGINEER" 的文档:

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

接下来,添加一个 $sort 阶段,按 DateOfBirth字段对文档进行降序排序,从而首先列出最年轻的人员:

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

接下来,向管道添加一个 $limit 阶段,以仅输出结果中的前三个文档。

.Limit(3)
4

最后,添加一个$project阶段。$project 阶段从结果文档中排除不必要的字段:

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

最后,在 IDE 中运行应用程序并检查结果。

聚合结果包含三个文档。这些文档代表了职业为"ENGINEER"的三个最年轻的人,按从幼到长的顺序排列。结果省略了 _idAddress 字段。

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

首先,添加一个 $match 阶段,用于查找 vocation字段的值为 "ENGINEER" 的文档:

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

接下来,添加一个 $sort 阶段,按 dateofbirth字段对文档进行降序排序,从而首先列出最年轻的人员:

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

接下来,向管道添加一个 $limit 阶段,以仅输出结果中的前三个文档。

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

最后,添加一个$unset阶段。$unset 阶段会从结果文档中删除不必要的字段:

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

提示

如果将具有不同字段的文档添加到集合中,请使用 $unset 操作符而不是 $project 来避免修改聚合管道。

5

将以下代码添加到应用程序末尾,以对personscollection执行聚合:

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

最后,在 shell 中运行以下命令以启动应用程序:

go run agg_tutorial.go
6

聚合结果包含三个文档。这些文档代表了职业为"ENGINEER"的三个最年轻的人,按从幼到长的顺序排列。结果省略了 _idaddress 字段。

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

首先,添加一个 $match 阶段,用于查找 vocation字段的值为 "ENGINEER" 的文档:

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

接下来,添加一个 $sort 阶段,按 dateofbirth字段对文档进行降序排序,从而首先列出最年轻的人员:

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

接下来,向管道添加一个 $limit 阶段,以仅输出结果中的前三个文档。

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

最后,添加一个$unset阶段。$unset 阶段会从结果文档中删除不必要的字段:

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

提示

如果将具有不同字段的文档添加到集合中,请使用 $unset 操作符而不是 $project 来避免修改聚合管道。

5

将以下代码添加到应用程序末尾,以对personscollection执行聚合:

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

最后,在 IDE 中运行应用程序。

6

聚合结果包含三个文档。这些文档代表了职业为"ENGINEER"的三个最年轻的人,按从幼到长的顺序排列。结果省略了 _idaddress 字段。

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

首先,添加一个 $match 阶段,用于查找 vocation字段的值为 "ENGINEER" 的文档:

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

接下来,添加一个 $sort 阶段,按 dateOfBirth字段对文档进行降序排序,从而首先列出最年轻的人员:

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

接下来,向管道添加一个 $limit 阶段,以仅输出结果中的前三个文档。

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

最后,添加一个$unset阶段。$unset 阶段会从结果文档中删除不必要的字段:

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

提示

如果将具有不同字段的文档添加到集合中,请使用 $unset 操作符而不是 $project 来避免修改聚合管道。

5

将以下代码添加到应用程序末尾,以对personscollection执行聚合:

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

最后,在 IDE 中运行应用程序。

6

聚合结果包含三个文档。这些文档代表了职业为"ENGINEER"的三个最年轻的人,按从幼到长的顺序排列。结果省略了 _idaddress 字段。

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

首先,添加一个 $match 阶段,用于查找 vocation字段的值为 "ENGINEER" 的文档:

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

接下来,添加一个 $sort 阶段,按 dateofbirth字段对文档进行降序排序,从而首先列出最年轻的人员:

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

接下来,向管道添加一个 $limit 阶段,以仅输出结果中的前三个文档。

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

最后,添加一个$unset阶段。$unset 阶段会从结果文档中删除不必要的字段:

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

提示

如果将具有不同字段的文档添加到集合中,请使用 $unset 操作符而不是 $project 来避免修改聚合管道。

5

将以下代码添加到应用程序末尾,以对personscollection执行聚合:

const aggregationResult = await persons.aggregate(pipeline);

最后,在 shell 中运行以下命令以启动应用程序:

node agg_tutorial.js
6

聚合结果包含三个文档。这些文档代表了职业为"ENGINEER"的三个最年轻的人,按从幼到长的顺序排列。结果省略了 _idaddress 字段。

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

Pipeline 实例中,创建一个$match 阶段,用于查找 vocation字段的值为 "ENGINEER" 的文档:

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

接下来,创建一个 $sort 阶段,按 dateofbirth字段降序对文档进行排序,从而首先列出最年轻的人:

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

接下来,为管道创建一个 $limit 阶段,以仅输出结果中的前三个文档。

Stage::limit(3),
4

最后,创建一个$unset阶段。$unset 阶段会从结果文档中删除不必要的字段:

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

提示

如果将具有不同字段的文档添加到集合中,请使用 $unset 操作符而不是 $project 来避免修改聚合管道。

5

将以下代码添加到应用程序末尾,以对personscollection执行聚合:

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

最后,在 shell 中运行以下命令以启动应用程序:

php agg_tutorial.php
6

聚合结果包含三个文档。这些文档代表了职业为"ENGINEER"的三个最年轻的人,按从幼到长的顺序排列。结果省略了 _idaddress 字段。

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

Pipeline 实例中,创建一个$match 阶段,用于查找 vocation字段的值为 "ENGINEER" 的文档:

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

接下来,创建一个 $sort 阶段,按 dateofbirth字段降序对文档进行排序,从而首先列出最年轻的人:

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

接下来,为管道创建一个 $limit 阶段,以仅输出结果中的前三个文档。

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

最后,创建一个$unset阶段。$unset 阶段会从结果文档中删除不必要的字段:

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

提示

如果将具有不同字段的文档添加到集合中,请使用 $unset 操作符而不是 $project 来避免修改聚合管道。

5

将以下代码添加到应用程序末尾,以对personscollection执行聚合:

aggregation_result = person_coll.aggregate(pipeline)

最后,在 shell 中运行以下命令以启动应用程序:

python3 agg_tutorial.py
6

聚合结果包含三个文档。这些文档代表了职业为"ENGINEER"的三个最年轻的人,按从幼到长的顺序排列。结果省略了 _idaddress 字段。

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

首先,添加一个 $match 阶段,用于查找 vocation字段的值为 "ENGINEER" 的文档:

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

接下来,添加一个 $sort 阶段,按 dateofbirth字段对文档进行降序排序,从而首先列出最年轻的人员:

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

接下来,向管道添加一个 $limit 阶段,以仅输出结果中的前三个文档。

{ "$limit": 3 },
4

最后,添加一个$unset阶段。$unset 阶段会从结果文档中删除不必要的字段:

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

提示

如果将具有不同字段的文档添加到集合中,请使用 $unset 操作符而不是 $project 来避免修改聚合管道。

5

将以下代码添加到应用程序末尾,以对personscollection执行聚合:

aggregation_result = persons.aggregate(pipeline)

最后,在 shell 中运行以下命令以启动应用程序:

node agg_tutorial.rb
6

聚合结果包含三个文档。这些文档代表了职业为"ENGINEER"的三个最年轻的人,按从幼到长的顺序排列。结果省略了 _idaddress 字段。

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

首先,添加一个 $match 阶段,用于查找 vocation字段的值为 "ENGINEER" 的文档:

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

接下来,添加一个 $sort 阶段,按 dateofbirth字段对文档进行降序排序,从而首先列出最年轻的人员:

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

接下来,向管道添加一个 $limit 阶段,以仅输出结果中的前三个文档。

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

最后,添加一个$unset阶段。$unset 阶段会从结果文档中删除不必要的字段:

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

提示

如果将具有不同字段的文档添加到集合中,请使用 $unset 操作符而不是 $project 来避免修改聚合管道。

5

将以下代码添加到应用程序末尾,以对personscollection执行聚合:

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

最后,在 shell 中运行以下命令以启动应用程序:

cargo run
6

聚合结果包含三个文档。这些文档代表了职业为"ENGINEER"的三个最年轻的人,按从幼到长的顺序排列。结果省略了 _idaddress 字段。

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

首先,添加一个 $match 阶段,用于查找 vocation字段的值为 "ENGINEER" 的文档:

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

接下来,添加一个 $sort 阶段,按 dateofbirth字段对文档进行降序排序,从而首先列出最年轻的人员:

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

接下来,向管道添加一个 $limit 阶段,以仅输出结果中的前三个文档。

Aggregates.limit(3),
4

最后,添加一个$unset阶段。$unset 阶段会从结果文档中删除不必要的字段:

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

提示

如果将具有不同字段的文档添加到集合中,请使用 $unset 操作符而不是 $project 来避免修改聚合管道。

5

将以下代码添加到应用程序末尾,以对personscollection执行聚合:

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

最后,在 IDE 中运行应用程序。

6

聚合结果包含三个文档。这些文档代表了职业为"ENGINEER"的三个最年轻的人,按从幼到长的顺序排列。结果省略了 _idaddress 字段。

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

后退

管道教程

在此页面上