-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray.go
More file actions
81 lines (67 loc) · 2.36 KB
/
array.go
File metadata and controls
81 lines (67 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package mgdb
import (
"context"
"fmt"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
)
func AddDocToArray[T any](db *mongo.Database, collection string, ObjectID primitive.ObjectID, arrayname string, newDoc T) (result *mongo.UpdateResult, err error) {
filter := bson.M{"_id": ObjectID}
update := bson.M{
"$push": bson.M{arrayname: newDoc},
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
result, err = db.Collection(collection).UpdateOne(ctx, filter, update)
if err != nil {
return
}
return
}
// memberToDelete := model.Userdomyikado{PhoneNumber: docuser.PhoneNumber}
func DeleteDocFromArray[T any](db *mongo.Database, collection string, ObjectID primitive.ObjectID, arrayname string, memberToDelete T) (result *mongo.UpdateResult, err error) {
filter := bson.M{"_id": ObjectID}
update := bson.M{
"$pull": bson.M{arrayname: memberToDelete},
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
result, err = db.Collection(collection).UpdateOne(ctx, filter, update)
if err != nil {
return
}
return
}
// Menentukan kondisi filter untuk elemen array yang ingin diupdate
// filterCondition := bson.M{"githubusername": "awangga"}
// Nilai baru yang ingin diupdate
// updatedFields := bson.M{"poin": 50}
func EditDocInArray(db *mongo.Database, collection string, ObjectID primitive.ObjectID, arrayname string, filterCondition bson.M, updatedFields bson.M) (result *mongo.UpdateResult, err error) {
// Membuat filter untuk menemukan dokumen dengan ID dan elemen array yang sesuai dengan kondisi filter
filter := bson.M{
"_id": ObjectID,
}
// Menambahkan kondisi filter untuk elemen dalam array
for key, value := range filterCondition {
filter[fmt.Sprintf("%s.%s", arrayname, key)] = value
}
// Membuat update map untuk mengubah elemen array yang sesuai
updateMap := bson.M{}
for key, value := range updatedFields {
updateMap[fmt.Sprintf("%s.$.%s", arrayname, key)] = value
}
// Membuat update menggunakan $set
update := bson.M{
"$set": updateMap,
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Melakukan update pada dokumen yang sesuai dengan filter
result, err = db.Collection(collection).UpdateOne(ctx, filter, update)
if err != nil {
return
}
return
}