英文:
Select values for specific key from all collections in MongoDB using GoLang
问题
我是你的中文翻译助手,以下是翻译好的内容:
我对GoLang和MongoDB技术还不熟悉。我在一个集合中创建了几个文档,当在单个集合中显示时,它显示如下;
我需要从集合中选择所有文档的 _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;
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论