3 回答

TA貢獻1862條經驗 獲得超7個贊
不確定你是否找到了答案,但我昨天為此奮斗了一個多小時。
我不肯定這會解決你的問題。我假設您正在嘗試根據您的輸入構建一個過濾器。最終我在嘗試傳遞數組時沒有使用 bson.A。
情況:試圖構建一個過濾器,其中一個 bson.D 元素是一個數組。
我以為我需要使用 bson.A。
我的初步假設:
return bson.D{
{"uuid", request.Uuid},
{"action", request.Action},
{"resource", bson.D{{"$in", bson.A{resourceStrings}}}},
}
哪里resourceStrings是一段字符串。
然而,這最終將構建一個看起來像 FILTER : [ {resource [{$in [[Orgs::Organizations::1 Orgs::Organizations::* Orgs::Organizations Orgs::*]]}]}]
*注意 $in 方法在這里尋找一個數組的數組。
我們想要的是: FILTER : [{uuid 80} {action UpdateOrganization} {resource [{$in [Orgs::Organizations::1 Orgs::Organizations::* Orgs::Organizations Orgs::*]}]}]
如果我們傳入字符串的文字數組,它將起作用......
return bson.D{
{"uuid", request.Uuid},
{"action", request.Action},
{"resource", bson.D{{"$in", bson.A{"Orgs::Organizations::1", "Orgs::Organizations::*", "Orgs::Organizations", "Orgs::*"}}}},
}
經過反復試驗,我發現 bson.D 會直接接受數組。
最終我解決了這個問題
return bson.D{
{"uuid", request.Uuid},
{"action", request.Action},
{"resource", bson.D{{"$in", resourceStrings}}},
}
從字面上看你的例子 - 如果你只是想將一個數組編組到一個 bson.A 嘗試:
bson.A{input}

TA貢獻1909條經驗 獲得超7個贊
這是我的代碼,用于根據存在于另一個集合中的 ID 刪除多個文檔。
我們首先從一個集合中收集所有 ID 并添加到一個切片中。然后我們使用刪除另一個集合中的文檔DeleteMany()
我正在展示相關代碼以保持代碼整潔。
杰森
[
{
"id": "602607bcfdc0548bfebbd0c7",
"subject": "SUBJECT",
"system": "SYSTEM",
"board": "BOARD",
"series": "SERIES",
"paper": "PAPER",
"year": "2021",
"month": "February",
"question_hex_ids": [
"602607bcfdc0548bfebbd0c4",
"602607bcfdc0548bfebbd0c5",
"602607bcfdc0548bfebbd0c6"
]
}
]
代碼
var hexIDCollection []primitive.ObjectID
database := db.Conn.Database("mydatabase")
question := database.Collection("questions")
//Iterating to collect IDs from paper
for k, _ := range mystruct.question_hex_ids {
// fetching all IDs and appending to slice
ids := mystruct.question_hex_ids[k]
hexID, err := primitive.ObjectIDFromHex(ids)
if err != nil {
fmt.Println("ObjectIDFromHex ERROR", err)
}
//Populating a slice of all the IDs
hexIDCollection = append(hexIDCollection, hexID)
}
filter := bson.D{
{"_id", bson.D{{"$in", hexIDCollection}}}, }
deleteResult, err1 := question.DeleteMany(ctx, filter)
if err != nil {
fmt.Println("Question Deletion Error", err1)
}
fmt.Println("All questions Deleted: ", deleteResult)
- 3 回答
- 0 關注
- 234 瀏覽
添加回答
舉報