亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何對嵌套文檔使用元素查詢運算符 ($exists)?

如何對嵌套文檔使用元素查詢運算符 ($exists)?

Go
江戶川亂折騰 2022-06-21 10:04:03
我正在嘗試使用 Go 查找嵌套文檔中是否存在字段。目前,該文檔如下所示。我正在嘗試查看該用戶的購物車中是否存在項目 ID 字段 - 5f15d53f205c36fa8b022089。使用 Mongo Compass,我能夠使用此過濾器命令成功查詢正確的文檔。{"_id": ObjectId('5f19a8950268ef67ce0c5124'), "shoppingCart.items.5f15d53f205c36fa8b022089": {$exists: true}} 我嘗試在 Go 中使用相同的語法,但我仍然沒有從結果中得到任何回報。cursor, err := customersCollection.Find(        ctx,        bson.M{"_id": customerID, "shoppingCart.items.5f15d53f205c36fa8b022089": bson.M{"$exists": true}},        options.Find().SetProjection(bson.M{"_id": 1}),    )     // This is how I am reading the results from the cursor. When    // printing the results, I get an empty array.    var results []bson.M    if err = cursor.All(ctx, &results); err != nil {        customerLog.Errorf(logger.LogError(logger.LogInfo()), err)    }    fmt.Printf("Products Result: %v\n", results)我找不到任何有關在過濾器參數中包含元素查詢運算符的正確方法的文檔。這是我正在使用的 Mongo 驅動程序,https://godoc.org/go.mongodb.org/mongo-driver/mongo編輯 1.0 我嘗試過的事情:使用 bson.D 而不是 bson.M。更新了代碼段。光標,錯誤:=customersCollection.Find(ctx,bson.D{{“_id”,customerID},{“shoppingCart.items.5f15d53f205c36fa8b022089”,bson.D{{“$exists”,true}}}},選項。 Find().SetProjection(bson.M{"_id": 1}), )
查看完整描述

2 回答

?
莫回無

TA貢獻1865條經驗 獲得超7個贊

如果您使用go.mongodb.org/mongo-driver/bson包,您可以執行以下操作:


query := bson.M{}

query["_id"] = bson.M{

    "$exists": true,

}

如果你愿意,你也可以通過使用包裝器來做更清潔:


type FilterQuery bson.M


func NewFilterQuery() FilterQuery {

    return FilterQuery(bson.M{})

}


func (q FilterQuery) SetIdExists(exist bool) FilterQuery {

    q["_id"] = bson.M{

        "$exists": exist,

    }

    return q

}

然后從您的代碼中,您可以執行類似的操作


query := NewFilterQuery()

query.SetIdExist(true)

..

cursor, err := customersCollection.Find(

        ctx,

        query,

    ) 

...


查看完整回答
反對 回復 2022-06-21
?
aluckdog

TA貢獻1847條經驗 獲得超7個贊

嘗試以下操作:


bson.D{

   {"$exists", true},

}

(我搜索了驅動程序的來源$exist。)


查看完整回答
反對 回復 2022-06-21
  • 2 回答
  • 0 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號