我想使用 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)
- 1 回答
- 0 关注
- 84 浏览
添加回答
举报
0/150
提交
取消