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

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

使用 golang 從 mongodb 集合中獲取特定的鍵值對

使用 golang 從 mongodb 集合中獲取特定的鍵值對

Go
一只甜甜圈 2023-04-17 16:05:58
我想使用 golang 動態地從 mongodb 集合中獲取特定的鍵值對。err := collection.Find(operations).Limit(2).All(&products)我該怎么做,但它必須是動態的,因為選擇鍵值對在我這邊發生了變化:收款文件:{    "_id" : 168,    "entity_id" : "168",    "type_id" : "simple",    "attribute_set_id" : "24",    "entity_type_id" : "4",    "created_at" : "2013-10-31 14:51:18",    "has_options" : "0",    "required_options" : "0",    "sku" : "AIC-19000-16",    "updated_at" : "2016-11-22 21:04:46",    "base_type" : 154,    "table_shape" : 164,    "manufacturer" : 15,    "delivery" : "Free Delivery & Setup",    "visibility" : 4,    "tax_class_id" : 2,    "status" : 1,    "enable_googlecheckout" : 1,    "discontinued" : 0,    "featured_fme" : 0,    "featured_product" : 0,    "amxnotif_hide_alert" : 1,    "is_recurring" : 0,    "condition" : 3043,    "ships" : null,    "ignore_wisepricer" : 0,    "fedexable" : null,    "dropshipped" : 0,    "verified_by" : 3301,    "reward_point_product" : null,    "mw_reward_point_sell_product" : null,    "ashley_sale" : 0,    "disable_amazonpayments" : 0,    "for_configurables" : null,    "rfm" : 0,    "mk_stockmessage" : false,    "mk_hideshipdate" : 0,    "reviews_counter" : 0,    "mpn" : "19000-16",    "name" : "After Eight Titanium Leg Rectangular Dining Table",    "style" : "73",    "furniture_type" : "76",    "meta_title" : "After Eight Titanium Leg Rectangular Dining Table,     19000-16, Aico Furniture",    "meta_description" : "After Eight Titanium Leg Rectangular Dining     Table from Aico Furniture, 19003-88",    "options_container" : "container2",    "url_key" : "after-eight-titanium-leg-rectangular-dining-table",    "url_path" : "after-eight-titanium-leg-rectangular-dining- }
查看完整描述

1 回答

?
Smart貓小萌

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

您所需的字段列在不符合預期規范的map[interface{}]interface{}Query.Select()。描述字段的最常見類型是bson.M,其中鍵應該是要檢索的字段的名稱。

因此,您必須bson.M從您的鍵中構造一個值,并將其與Query.Select().?為此,我們必須找到一種方法將值從interface{}type 轉換為string.?最簡單和最方便的方法是使用fmt.Sprint()這個。

這是一個如何做到這一點的例子:

// Example input:

fields := map[interface{}]interface{}{

? ? 3: "name",

? ? 1: "manufacturer",

? ? 9: "sku",

}


fields2 := bson.M{}

for _, name := range fields {

? ? fields2[fmt.Sprint(name)] = 1

}


err := collection.Find(operations).Select(fields2).Limit(2).All(&products)


查看完整回答
反對 回復 2023-04-17
  • 1 回答
  • 0 關注
  • 116 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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