Skip to content

Commit b82f98b

Browse files
authored
DOCSP-53450: Cross-collection code fixes (#14209)
* DOCSP-53450: Cross-collection code fixes * fix build errors * EF feedback * kotlin fix
1 parent aafe339 commit b82f98b

15 files changed

+76
-171
lines changed

content/atlas/source/includes/fts/materialized-view/CreateUpdateView.java

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,6 @@
1818
public class CreateUpdateView {
1919

2020
private static void updateMonthlyPhoneTransactions(MongoClient client, MongoCollection<Document> collection) {
21-
MongoDatabase database = client.getDatabase("sample_supplies");
22-
MongoCollection<Document> monthlyPhoneTransactions = database.getCollection("monthlyPhoneTransactions");
23-
2421
// Create the aggregation pipeline
2522
List<Document> pipeline = Arrays.asList(
2623
new Document("$match", new Document("purchaseMethod", "Phone")),
@@ -31,20 +28,14 @@ private static void updateMonthlyPhoneTransactions(MongoClient client, MongoColl
3128
.append("sales_quantity", new Document("$sum", "$items.quantity"))
3229
.append("sales_price", new Document("$sum", "$items.price"))
3330
),
34-
new Document("$set", new Document("sales_price", new Document("$toDouble", "$sales_price")))
31+
new Document("$set", new Document("sales_price", new Document("$toDouble", "$sales_price"))),
32+
new Document("$merge", new Document("into", "monthlyPhoneTransactions")
33+
.append("whenMatched", "replace"))
3534
);
3635

37-
// Execute the aggregation
36+
// Run the aggregation
3837
AggregateIterable<Document> results = collection.aggregate(pipeline);
39-
40-
// Process and save the results to monthlyPhoneTransactions
41-
for (Document doc : results) {
42-
// For each result, upsert into the materialized view
43-
Document filter = new Document("_id", doc.get("_id"));
44-
ReplaceOptions options = new ReplaceOptions().upsert(true);
45-
46-
monthlyPhoneTransactions.replaceOne(filter, doc, options);
47-
}
38+
results.toCollection();
4839
}
4940

5041
public static void main(String[] args) {

content/atlas/source/includes/fts/materialized-view/CreateUpdateView.kt

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,6 @@ class CreateUpdateView {
1010

1111
companion object {
1212
private suspend fun updateMonthlyPhoneTransactions(client: MongoClient, collection: MongoCollection<Document>) {
13-
val database = client.getDatabase("sample_supplies")
14-
val monthlyPhoneTransactions = database.getCollection<Document>("monthlyPhoneTransactions")
15-
1613
// Create the aggregation pipeline
1714
val pipeline = listOf(
1815
Document("\$match", Document("purchaseMethod", "Phone")),
@@ -23,20 +20,14 @@ class CreateUpdateView {
2320
.append("sales_quantity", Document("\$sum", "\$items.quantity"))
2421
.append("sales_price", Document("\$sum", "\$items.price"))
2522
),
26-
Document("\$set", Document("sales_price", Document("\$toDouble", "\$sales_price")))
23+
Document("\$set", Document("sales_price", Document("\$toDouble", "\$sales_price"))),
24+
Document("\$merge", Document("into", "monthlyPhoneTransactions")
25+
.append("whenMatched", "replace"))
2726
)
2827

29-
// Execute the aggregation
28+
// Run the aggregation
3029
val results = collection.aggregate<Document>(pipeline)
31-
32-
// Process and save the results to monthlyPhoneTransactions
33-
results.collect { doc ->
34-
// For each result, upsert into the materialized view
35-
val filter = Document("_id", doc["_id"])
36-
val options = ReplaceOptions().upsert(true)
37-
38-
monthlyPhoneTransactions.replaceOne(filter, doc, options)
39-
}
30+
results.toCollection()
4031
}
4132

4233
@JvmStatic

content/atlas/source/includes/fts/materialized-view/create-update-view.c

Lines changed: 10 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -56,17 +56,13 @@
5656
return 0;
5757
}
5858

59-
void update_monthly_phone_transactions(mongoc_client_t *client, mongoc_collection_t *collection)
59+
void update_monthly_phone_transactions(mongoc_client_t *client, mongoc_collection_t *collection)
6060
{
61-
mongoc_collection_t *monthly_phone_transactions;
6261
bson_t *pipeline;
6362
mongoc_cursor_t *cursor;
6463
const bson_t *doc;
6564
bson_error_t error;
6665

67-
/* Get materialized view handle */
68-
monthly_phone_transactions = mongoc_client_get_collection(client, "sample_supplies", "monthlyPhoneTransactions");
69-
7066
/* Create the aggregation pipeline */
7167
pipeline = BCON_NEW (
7268
"pipeline", "[",
@@ -81,43 +77,25 @@
8177
"sales_price", "{", "$sum", BCON_UTF8("$items.price"), "}",
8278
"}", "}",
8379
"{", "$set", "{", "sales_price", "{", "$toDouble", BCON_UTF8("$sales_price"), "}", "}", "}",
80+
"{", "$merge", "{", "into", BCON_UTF8("monthlyPhoneTransactions"), "whenMatched", BCON_UTF8("replace"), "}", "}",
8481
"]"
8582
);
8683

87-
/* Execute the aggregation */
84+
/* Run the aggregation */
8885
cursor = mongoc_collection_aggregate(
8986
collection, MONGOC_QUERY_NONE, pipeline, NULL, NULL);
90-
91-
/* Process and save the results to monthlyPhoneTransactions */
87+
9288
while (mongoc_cursor_next(cursor, &doc)) {
93-
/* For each result, upsert into the materialized view */
94-
bson_t *query = bson_new();
95-
bson_t *update = bson_copy(doc);
96-
bson_t *opts = BCON_NEW("upsert", BCON_BOOL(true));
97-
98-
/* Extract the _id field from the aggregation result */
99-
bson_iter_t iter;
100-
if (bson_iter_init_find(&iter, doc, "_id")) {
101-
bson_append_value(query, "_id", 3, bson_iter_value(&iter));
102-
}
103-
104-
mongoc_collection_replace_one(
105-
monthly_phone_transactions,
106-
query,
107-
update,
108-
opts,
109-
NULL,
110-
&error
111-
);
112-
113-
bson_destroy(query);
114-
bson_destroy(update);
115-
bson_destroy(opts);
89+
/* Consume the cursor to execute the pipeline */
90+
}
91+
92+
93+
if (mongoc_cursor_error(cursor, &error)) {
94+
fprintf(stderr, "Aggregation error: %s\n", error.message);
11695
}
11796

11897
/* Clean up */
11998
bson_destroy(pipeline);
12099
mongoc_cursor_destroy(cursor);
121100
mongoc_collection_destroy(collection);
122-
mongoc_collection_destroy(monthly_phone_transactions);
123101
}

content/atlas/source/includes/fts/materialized-view/create-update-view.cpp

Lines changed: 6 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,6 @@ using bsoncxx::builder::stream::open_document;
1919

2020
// Function to update the materialized view
2121
void update_monthly_phone_transactions(mongocxx::client& client, mongocxx::collection collection) {
22-
auto monthly_phone_transactions = client["sample_supplies"]["monthlyPhoneTransactions"];
23-
2422
// Create the aggregation pipeline
2523
auto pipeline = mongocxx::pipeline{};
2624
pipeline.match(document{} << "purchaseMethod" << "Phone" << finalize);
@@ -39,31 +37,15 @@ void update_monthly_phone_transactions(mongocxx::client& client, mongocxx::colle
3937
pipeline.add_fields(document{} << "sales_price" << open_document
4038
<< "$toDouble" << "$sales_price"
4139
<< close_document << finalize);
40+
pipeline.merge(document{} << "into" << "monthlyPhoneTransactions"
41+
<< "whenMatched" << "replace" << finalize);
4242

43-
// Execute the aggregation
43+
// Run the aggregation
4444
auto cursor = collection.aggregate(pipeline);
4545

46-
// Process and save the results to monthlyPhoneTransactions
47-
for (auto&& doc : cursor) {
48-
49-
// Extract the `_id` field
50-
auto id_element = doc["_id"];
51-
52-
// Create the filter document for the operation
53-
bsoncxx::builder::basic::document filter_builder;
54-
filter_builder.append(bsoncxx::builder::basic::kvp("_id", id_element.get_string().value));
55-
56-
// Prepare upsert options
57-
auto options = mongocxx::options::replace{};
58-
options.upsert(true);
59-
60-
// Perform the replace operation
61-
try {
62-
monthly_phone_transactions.replace_one(filter_builder.view(), doc, options);
63-
} catch (const std::exception& e) {
64-
std::cerr << "Error replacing document: " << e.what() << std::endl;
65-
}
66-
}
46+
for (auto&& doc : cursor) {
47+
// Consume the cursor to execute the pipeline
48+
}
6749
}
6850

6951
int main() {

content/atlas/source/includes/fts/materialized-view/create-update-view.cs

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,6 @@ static async Task Main(string[] args)
4949

5050
static async Task UpdateMonthlyPhoneTransactions(MongoClient client, IMongoCollection<BsonDocument> collection)
5151
{
52-
var database = client.GetDatabase("sample_supplies");
53-
var monthlyPhoneTransactions = database.GetCollection<BsonDocument>("monthlyPhoneTransactions");
54-
5552
// Create the aggregation pipeline
5653
var pipeline = new BsonDocument[]
5754
{
@@ -68,22 +65,16 @@ static async Task UpdateMonthlyPhoneTransactions(MongoClient client, IMongoColle
6865
{ "sales_quantity", new BsonDocument("$sum", "$items.quantity") },
6966
{ "sales_price", new BsonDocument("$sum", "$items.price") }
7067
}),
71-
new BsonDocument("$set", new BsonDocument("sales_price", new BsonDocument("$toDouble", "$sales_price")))
72-
};
73-
74-
// Execute the aggregation
75-
using (var cursor = await collection.AggregateAsync<BsonDocument>(pipeline))
76-
{
77-
// Process and save the results to monthlyPhoneTransactions
78-
await cursor.ForEachAsync(async doc =>
68+
new BsonDocument("$set", new BsonDocument("sales_price", new BsonDocument("$toDouble", "$sales_price"))),
69+
new BsonDocument("$merge", new BsonDocument
7970
{
80-
// For each result, upsert into the materialized view
81-
var filter = Builders<BsonDocument>.Filter.Eq("_id", doc["_id"]);
82-
var options = new ReplaceOptions { IsUpsert = true };
83-
84-
await monthlyPhoneTransactions.ReplaceOneAsync(filter, doc, options);
85-
});
86-
}
71+
{ "into", "monthlyPhoneTransactions" },
72+
{ "whenMatched", "replace" }
73+
})
74+
};
75+
76+
// Run the aggregation
77+
await collection.AggregateAsync<BsonDocument>(pipeline);
8778
}
8879
}
8980
}

content/atlas/source/includes/fts/materialized-view/create-update-view.go

Lines changed: 16 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -12,53 +12,33 @@ import (
1212
)
1313

1414
func updateMonthlyPhoneTransactions(ctx context.Context, client *mongo.Client, collection *mongo.Collection) error {
15-
monthlyPhoneTransactions := client.Database("sample_supplies").Collection("monthlyPhoneTransactions")
16-
1715
// Create the aggregation pipeline
18-
matchStage := bson.D{{Key: "$match", Value: bson.D{{Key: "purchaseMethod", Value: "Phone"}}}}
19-
unwindStage := bson.D{{Key: "$unwind", Value: bson.D{{Key: "path", Value: "$items"}}}}
20-
groupStage := bson.D{{Key: "$group", Value: bson.D{
21-
{Key: "_id", Value: bson.D{
22-
{Key: "$dateToString", Value: bson.D{
23-
{Key: "format", Value: "%Y-%m"},
24-
{Key: "date", Value: "$saleDate"},
16+
matchStage := bson.D{bson.E{Key: "$match", Value: bson.D{bson.E{Key: "purchaseMethod", Value: "Phone"}}}}
17+
unwindStage := bson.D{bson.E{Key: "$unwind", Value: bson.D{bson.E{Key: "path", Value: "$items"}}}}
18+
groupStage := bson.D{bson.E{Key: "$group", Value: bson.D{
19+
bson.E{Key: "_id", Value: bson.D{
20+
bson.E{Key: "$dateToString", Value: bson.D{
21+
bson.E{Key: "format", Value: "%Y-%m"},
22+
bson.E{Key: "date", Value: "$saleDate"},
2523
}},
2624
}},
27-
{Key: "sales_quantity", Value: bson.D{{Key: "$sum", Value: "$items.quantity"}}},
28-
{Key: "sales_price", Value: bson.D{{Key: "$sum", Value: "$items.price"}}},
25+
bson.E{Key: "sales_quantity", Value: bson.D{bson.E{Key: "$sum", Value: "$items.quantity"}}},
26+
bson.E{Key: "sales_price", Value: bson.D{bson.E{Key: "$sum", Value: "$items.price"}}},
27+
}}}
28+
setStage := bson.D{bson.E{Key: "$set", Value: bson.D{bson.E{Key: "sales_price", Value: bson.D{bson.E{Key: "$toDouble", Value: "$sales_price"}}}}}}
29+
mergeStage := bson.D{bson.E{Key: "$merge", Value: bson.D{
30+
bson.E{Key: "into", Value: "monthlyPhoneTransactions"},
31+
bson.E{Key: "whenMatched", Value: "replace"},
2932
}}}
30-
setStage := bson.D{{Key: "$set", Value: bson.D{{Key: "sales_price", Value: bson.D{{Key: "$toDouble", Value: "$sales_price"}}}}}}
3133

32-
pipeline := mongo.Pipeline{matchStage, unwindStage, groupStage, setStage}
34+
pipeline := mongo.Pipeline{matchStage, unwindStage, groupStage, setStage, mergeStage}
3335

34-
// Execute the aggregation
36+
// Run the aggregation
3537
cursor, err := collection.Aggregate(ctx, pipeline)
3638
if err != nil {
3739
return err
3840
}
3941
defer cursor.Close(ctx)
40-
41-
// Process and save the results to monthlyPhoneTransactions
42-
for cursor.Next(ctx) {
43-
var doc bson.M
44-
if err := cursor.Decode(&doc); err != nil {
45-
return err
46-
}
47-
48-
// For each result, upsert into the materialized view
49-
filter := bson.M{"_id": doc["_id"]}
50-
opts := options.Replace().SetUpsert(true)
51-
52-
_, err := monthlyPhoneTransactions.ReplaceOne(ctx, filter, doc, opts)
53-
if err != nil {
54-
return err
55-
}
56-
}
57-
58-
if err := cursor.Err(); err != nil {
59-
return err
60-
}
61-
6242
return nil
6343
}
6444

content/atlas/source/includes/fts/materialized-view/create-update-view.js

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,6 @@ const schedule = require('node-schedule');
33

44
// Function to update the materialized view
55
async function updateMonthlyPhoneTransactions(client, collection) {
6-
const database = client.db('sample_supplies');
7-
const monthlyPhoneTransactions = database.collection('monthlyPhoneTransactions');
8-
96
// Create the aggregation pipeline
107
const pipeline = [
118
{ $match: { purchaseMethod: 'Phone' } },
@@ -22,20 +19,20 @@ async function updateMonthlyPhoneTransactions(client, collection) {
2219
sales_price: { $sum: '$items.price' }
2320
}
2421
},
25-
{ $set: { sales_price: { $toDouble: '$sales_price' } } }
22+
{ $set: { sales_price: { $toDouble: '$sales_price' } } },
23+
{
24+
$merge: {
25+
into: 'monthlyPhoneTransactions',
26+
whenMatched: 'replace'
27+
}
28+
}
2629
];
2730

28-
// Execute the aggregation
31+
// Run the aggregation
2932
const cursor = collection.aggregate(pipeline);
3033

31-
// Process and save the results to monthlyPhoneTransactions
3234
for await (const doc of cursor) {
33-
// For each result, upsert into the materialized view
34-
await monthlyPhoneTransactions.replaceOne(
35-
{ _id: doc._id },
36-
doc,
37-
{ upsert: true }
38-
);
35+
// Consume the cursor to execute the pipeline
3936
}
4037
}
4138

@@ -74,6 +71,8 @@ async function main() {
7471

7572
} catch (err) {
7673
console.error('Error:', err);
74+
} finally {
75+
await client.close();
7776
}
7877
}
7978

content/atlas/source/includes/fts/materialized-view/create-update-view.py

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@
55

66
def update_monthly_phone_transactions(client, collection):
77
"""Update the materialized view of monthly phone transactions."""
8-
monthly_phone_transactions = client.sample_supplies.monthlyPhoneTransactions
9-
108
# Create the aggregation pipeline
119
pipeline = [
1210
{"$match": {"purchaseMethod": "Phone"}},
@@ -21,20 +19,15 @@ def update_monthly_phone_transactions(client, collection):
2119
"sales_quantity": {"$sum": "$items.quantity"},
2220
"sales_price": {"$sum": "$items.price"}
2321
}},
24-
{"$set": {"sales_price": {"$toDouble": "$sales_price"}}}
22+
{"$set": {"sales_price": {"$toDouble": "$sales_price"}}},
23+
{"$merge": {
24+
"into": "monthlyPhoneTransactions",
25+
"whenMatched": "replace"
26+
}}
2527
]
2628

27-
# Execute the aggregation
28-
cursor = collection.aggregate(pipeline)
29-
30-
# Process and save the results to monthlyPhoneTransactions
31-
for doc in cursor:
32-
# For each result, upsert into the materialized view
33-
monthly_phone_transactions.replace_one(
34-
{"_id": doc["_id"]},
35-
doc,
36-
upsert=True
37-
)
29+
# Run the aggregation
30+
collection.aggregate(pipeline)
3831

3932
def scheduled_update(client, sales, purchase_orders):
4033
"""Run the monthly update task."""

content/atlas/source/includes/fts/tutorials/facet/steps-create-index-c.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ collection.
3333
:linenos:
3434
:copyable:
3535

36-
.. include:: /includes/fts/field-types/find-connection-string.rst
36+
.. include:: /includes/search-shared/find-connection-string.rst
3737

3838
.. step:: Set up a CMake application
3939

0 commit comments

Comments
 (0)