dongshou7903 2019-03-03 23:24
浏览 33
已采纳

聚合管道相对于CLI返回错误的结果

I have a collection in mongo on which I run the following query

db.feeds.aggregate({"$match":{createdat:"20190203"}}, {"$group": {_id: {"type": "$type"}, total: {$sum: 1} }},{"$project":   {"type": "$_id.type", "tot": "$total", "_id": 0} }   )

It works as expected and returns,

{ "type" : "f", "tot" : 1 }
{ "type" : "ebm", "tot" : 1 }
{ "type" : "b", "tot" : 3 }

However, when I try replicating the pipeline in Golang, as follow:

    pipeline := []bson.M{
    // match
    {"$match": bson.M{"createdat": when}},
    // group
    {"$group": bson.M{
        "_id":        bson.M{"type": "$type"}, // "$fieldname" - return the field
        "TotalFeeds": bson.M{"$sum": 1}}},
    // project
    {"$project": bson.M{"type": "$_id.type", // project selects subset of fields
        "TotalFeeds": "$TotalFeeds", // rename fiedls
        "_id":        0}},           // 0 means not show _id
}

The returned count is 0.

map[$match:map[createdat:20190203]] map[$group:map[TotalFeeds:map[$sum:1] _id:map[type:$type]]] map[$project:map[type:$_id.type TotalFeeds:$TotalFeeds _id:0]]]
{f 0  }
{ebm 0  }
{b 0  }
[{f 0  } {ebm 0  } {b 0  }]

Below the entire function I am using in Golang:

func CountFeeds(when string) Feeds {

    ctx, _ := context.WithTimeout(context.Background(), 60*time.Second)

    pipeline := []bson.M{
        // match
        {"$match": bson.M{"createdat": when}},
        // group
        {"$group": bson.M{
            "_id":        bson.M{"type": "$type"}, // "$fieldname" - return the field
            "TotalFeeds": bson.M{"$sum": 1}}},
        // project
        {"$project": bson.M{"type": "$_id.type", // project select subset of fields
            "TotalFeeds": "$TotalFeeds", // rename fiedls
            "_id":        0}},           // 0 means not show _id
    }


    fmt.Println(pipeline)
    curs, err := db.Collection("feeds").Aggregate(ctx, pipeline)
    utilities.Catch(err)

    defer curs.Close(ctx)

    element := Feeds{}
    e := []Feeds{}
    for curs.Next(ctx) {
        err := curs.Decode(&element)
        fmt.Println(element)
        utilities.Catch(err)
        e = append(e, element)
    }

    fmt.Println(e)
    return element
}
  • 写回答

1条回答 默认 最新

  • dongqianzhan8325 2019-03-05 07:12
    关注

    First, use bson.D{} instead of bson.M{}. This is because bson.D{} should be used in situations where order matters, such as MongoDB commands.

    You can also encapsulate the whole pipeline in mongo.Pipeline. For example:

    pipeline := mongo.Pipeline{
        {{"$match", bson.D{{"createdata", 10}}}},
        {{"$group", bson.D{
            {"_id",        bson.D{{"type", "$type"}}}, 
            {"TotalFeeds", bson.D{{"$sum", 1}}},
        }}},
        {{"$project", bson.D{
            {"type", "$_id.type"}, 
            {"TotalFeeds", "$TotalFeeds"}, 
            {"_id", 0}},
        }},          
    }
    

    Check your Feeds{} struct mapping. Make sure, either you specify the bson mapping, i.e. :

    type Feeds struct {
        Type string `bson:"type"`
        TotalFeeds int `bson:"TotalFeeds"`
    }
    

    Or, in your projection stage $project you use consistent casing for the fields. For example, specify all lower case type and totalfeeds or all upper case Type and TotalFeeds.

    pipeline := mongo.Pipeline{
        {{"$match", bson.D{{"createdata", 10}}}},
        {{"$group", bson.D{
            {"_id",        bson.D{{"type", "$type"}}}, 
            {"totalfeeds", bson.D{{"$sum", 1}}},
        }}},
        {{"$project", bson.D{
            {"type", "$_id.type"}, 
            {"totalfeeds", "$totalfeeds"}, 
            {"_id", 0}},
        }},      
    }
    

    Then you don't have to specify the bson mapping in the struct:

    type MyStruct struct {
        Type string 
        Total int
    }
    

    So either use consistent field name cases in your struct, or explicitly provide the bson mapping.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 Ubuntu20.04无法连接GitHub
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥30 C++行情软件的tick数据如何高效的合成K线