英文:
How to return multiple values using Go Mongo Distinct
问题
我想从集合中返回值,其中一个是批次(batch),它应该与特定的过滤器不同,即value="Nice",另一个是vendor。我无法获取vendor的值。
如何使用Distinct实现这一点?我需要使用Find()吗?
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
filter := bson.D{{Key: "batch", Value: ""}}
values, err := db.Collection("xyzcollection").Distinct(ctx, "batch", filter)
if err != nil {
return nil, err
}
batch := make([]string, len(values))
for i, v := range values {
batch[i] = v.(string)
}
fmt.Println(batch)
英文:
I want to return values from collection one is batch which should be distinct with specific filter i.e value="Nice" and another is vendor. I am unable to get vendor values?
How to achieve this using Distinct, Do I have to use Find()?
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
filter := bson.D{{Key: "batch", Value: ""}}
values, err := db.Collection("xyzcollection").Distinct(ctx, "batch", filter)
if err != nil {
return nil, err
}
batch := make([]string, len(values))
for i, v := range values {
batch[i] = v.(string)
}
fmt.Println(batch)
答案1
得分: 1
在Prasad的评论后,我用以下解决方案解决了我的问题。
type Example struct {}
var exm []Example
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
pipeline := []bson.M{
{"$match": bson.M{"status": "Pending"}},
{"$group": bson.M{"_id": "$batch"}},
}
cursor, err := db.Collection("xyzcollection").Aggregate(ctx, pipeline)
if err != nil {
return []Example{}, errors.New(fmt.Sprintf("无法检索数据:%s", err.Error()))
}
var result Example
for cursor.Next(ctx) {
cursor.Decode(&result)
exm = append(exm, result)
}
return exm, nil
英文:
After prasad comment I have solved my problem with this solution.
type Example struct {}
var exm []Example
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
pipeline := []bson.M{
{"$match": bson.M{"status": "Pending"}},
{"$group": bson.M{"_id": "$batch"}},
}
cursor, err := db.Collection("xyzcollection").Aggregate(ctx, pipeline)
if err != nil {
return []Example{}, errors.New(fmt.Sprintf("unable to retrive data: %s ", err.Error()))
}
var result Example
for cursor.Next(ctx) {
cursor.Decode(&result)
exm = append(exm, result)
}
return exm, nil
答案2
得分: -1
我找到了一个类似的问题,
你需要使用db.collection.aggregate
查询。请在MongoDB文档中阅读相关内容。
英文:
I found a similar question,
You have to use db.collection.aggregate
query. Please read it on MongoDB docs
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论