dougu3988 2017-05-24 10:15 采纳率: 100%
浏览 594
已采纳

MongoDB $ ifNull条件与mgo

I'm struggling porting a query from the mongo console to my Go code. I'm new to MongoDB so there might be additional mistakes I haven't taken into account.

Sample data 'users' collection:

{ "_id" : ObjectId("592400188d84961b7f34b0cd"), "username" : "randomUser2", "location" : { "type" : "Point", "coordinates" : [ -17.282573, 63.755657 ] } }
{ "_id" : ObjectId("592400188d84961b7f34b0ce"), "username" : "randomUser1", "location" : { "type" : "Point", "coordinates" : [ -17.634135, 65.705665 ] } }

Sample data 'newscounter' collection:

{ "_id" : ObjectId("592400188d84961b7f34b0cd"), "count" : 14 }

The query in mongo looks like this:

db.users.aggregate([
     { $geoNear: { 
         near: { type: "Point", coordinates: [-21.861198,64.120877] },
         distanceField: "distance",
         maxDistance: myDistance * 1000,
         spherical: true }
     },
    {
        $sort: { "distance": 1 }
    },
    {
     $lookup: {
        from: "newscounter",
        localField: "_id",
        foreignField: "_id",
        as: "news_count" }
    },
    {
        $unwind: { path: "$news_count", preserveNullAndEmptyArrays: true }
    },
    {
        $project : { 
            "id": 1,
            "username": 1,
            "distance": 1,
            "news_count": { $ifNull : ["$news_count.count", 0] }
        }
    }
])

The output is (I used random values for the calculated distance field here):

{ "_id" : ObjectId("592400188d84961b7f34b0cd"), "username" : "randomUser2", "distance" : 123, "news_count" : 14 }
{ "_id" : ObjectId("592400188d84961b7f34b0ce"), "username" : "randomUser1", "distance" : 456, "news_count" : 0 }

The part I've trouble with is the $ifNull in the $project stage.

How do I build the $ifNull line in Go using the mgo package?

I tried with:

"news_count": bson.M{
    "$ifNull": [2]interface{}{"$news_count.count", 0},
}

but it returns always an empty string for the news_count field.

Any help is greatly appreciated!

EDIT [solved]:

The issue was silly, I had the wrong type for the news_count field in the Go struct.

For the sake of completeness the pipeline in Go is:

p := []bson.M{
        bson.M{
            "$geoNear": bson.M{
                "near":          bson.M{"type": "Point", "coordinates": center},
                "distanceField": "distance",
                "maxDistance":   maxDistance,
                "spherical":     true,
            },
        },
        bson.M{
            "$sort": bson.M{
                "distance": 1,
            },
        },
        bson.M{
            "$lookup": bson.M{
                "from":         "newscount",
                "localField":   "_id",
                "foreignField": "_id",
                "as":           "news_count",
            },
        },
        bson.M{
            "$unwind": bson.M{
                "path": "$news_count",
                "preserveNullAndEmptyArrays": true,
            },
        },
        bson.M{
            "$project": bson.M{
                "_id":      1,
                "username": 1,
                "distance": 1,
                "news_count": bson.M{
                    "$ifNull": []interface{}{"$news_count.count", 0.0},
                },
            },
        },
    }

The result struct:

type Result struct {
          ID        bson.ObjectId  `json:"id" bson:"_id"`
          Username  string         `json:"username" bson:"username"`
          Distance  int64          `json:"distance" bson:"distance"`
          NewsCount int64          `json:"news_count" bson:"news_count"`
      }
  • 写回答

1条回答 默认 最新

  • dongzhuo3376 2017-05-24 10:47
    关注

    Your news_count projection works, the error is somewhere else in the code which you haven't posted.

    See this full, working example:

    cu := sess.DB("").C("users")
    cnc := sess.DB("").C("newscounter")
    
    he := func(err error) {
        if err != nil {
            panic(err)
        }
    }
    
    he(cu.Insert(
        bson.M{
            "_id":      bson.ObjectIdHex("592400188d84961b7f34b0ce"),
            "username": "randomuser1",
            "location": bson.M{
                "type":        "Point",
                "coordinates": []interface{}{-17.634135, 65.705665},
            },
        },
        bson.M{
            "_id":      bson.ObjectIdHex("592400188d84961b7f34b0cd"),
            "username": "randomuser2",
            "location": bson.M{
                "type":        "Point",
                "coordinates": []interface{}{-17.282573, 63.755657},
            },
        },
    ))
    he(cnc.Insert(
        bson.M{
            "_id":   bson.ObjectIdHex("592400188d84961b7f34b0cd"),
            "count": 14,
        },
    ))
    
    pipe := cu.Pipe([]bson.M{
        {
            "$geoNear": bson.M{
                "near": bson.M{
                    "type":        "Point",
                    "coordinates": []interface{}{-21.861198, 64.120877},
                },
                "distanceField": "distance",
                "maxDistance":   123456789,
                "spherical":     true,
            },
        },
        {
            "$sort": bson.M{"distance": 1},
        },
        {
            "$lookup": bson.M{
                "from":         "newscounter",
                "localField":   "_id",
                "foreignField": "_id",
                "as":           "news_count",
            },
        },
        {
            "$unwind": bson.M{
                "path": "$news_count",
                "preserveNullAndEmptyArrays": true,
            },
        },
        {
            "$project": bson.M{
                "id":       1,
                "username": 1,
                "distance": 1,
                "news_count": bson.M{
                    "$ifNull": []interface{}{"$news_count.count", 0},
                },
            },
        },
    })
    
    it := pipe.Iter()
    
    fmt.Println()
    m := bson.M{}
    for it.Next(&m) {
        fmt.Println(m)
        fmt.Println()
    }
    he(it.Err())
    

    Output:

    map[_id:ObjectIdHex("592400188d84961b7f34b0cd") username:randomuser2 distance:227534.08191011765 news_count:14]
    
    map[username:randomuser1 distance:266222.98643136176 news_count:0 _id:ObjectIdHex("592400188d84961b7f34b0ce")]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试