Select values for specific key from all collections in MongoDB using GoLang

huangapple go评论157阅读模式
英文:

Select values for specific key from all collections in MongoDB using GoLang

问题

我是你的中文翻译助手,以下是翻译好的内容:

我对GoLang和MongoDB技术还不熟悉。我在一个集合中创建了几个文档,当在单个集合中显示时,它显示如下;
Select values for specific key from all collections in MongoDB using GoLang

我需要从集合中选择所有文档的 _id,类似于 SQL SELECT _id FROM Docs
我没有找到使用GoLang解决这个问题的方法。但是我尝试选择所有文档,然后从中筛选出 _id。

collection, err := db.GetDBCollectionUnzip("docs")
var res model.ResponseResult

findOptions := options.Find()
findOptions.SetLimit(2)

var results []*map[string]interface{}

cur, err := collection.Find(context.TODO(), bson.D{{}}, findOptions)

由于文档内容较大,这种方法可能耗时较长。我希望能得到关于这个问题的指导。提前谢谢你。

英文:

I'm new to GoLang and MongoDB technologies. I created several documents in a collection and when it is displayed in a single collection, it shows;
Select values for specific key from all collections in MongoDB using GoLang

I need to select only the _id from all the documents in the collection similarly to SQL SELECT _id FROM Docs
I didn't find a method to solve this problem using GoLang. But I tried select all the documents and filter the _id from all

collection, err := db.GetDBCollectionUnzip("docs")
	var res model.ResponseResult

	findOptions := options.Find()
	findOptions.SetLimit(2)


	var results []*map[string]interface{}

	cur, err := collection.Find(context.TODO(), bson.D{{}}, findOptions) 

Since the document content is large, it seems to be a time consuming approach. I hope a guidance for this matter. Thank you in advance.

答案1

得分: 0

最终我找到了解决方案。这对任何感兴趣的人可能会有所帮助。

findOptions := options.Find().SetProjection(bson.M{"_id": 1})
findOptions.SetLimit(2)
cur, err := collection.Find(context.TODO(), bson.D{{}}, findOptions)
英文:

Finally I was able to find the solution. This may be helpful for anyone who is interested.

findOptions := options.Find().SetProjection(bson.M{"_id": 1})
findOptions.SetLimit(2)
cur, err := collection.Find(context.TODO(), bson.D{{}}, findOptions)

huangapple
  • 本文由 发表于 2021年5月19日 05:02:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/67593920.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定