MongoDB $ ifNull与mgo有条件

时间:2017-05-24 10:15:33

标签: mongodb go aggregation-framework mgo

我正在努力将查询从mongo控制台移植到我的Go代码。 我是MongoDB的新手,所以可能还有其他错误我没有考虑过。

示例数据'用户'集合:

import codecs

URL = "http://api.songkick.com/api/3.0/search/artists.json" # no need to redefine this

with codecs.open("artistnames.csv", "r", "utf-8") as f:
    for a in f:
        artist = a.strip()
        r = requests.get(URL, params={"query": artist, "apikey": ""})
        # etc.

示例数据'newscounter'集合:

{ "_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 ] } }

mongo中的查询如下所示:

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

输出是(我在这里使用了计算距离字段的随机值):

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] }
        }
    }
])

我遇到麻烦的部分是$ project阶段的$ ifNull。

如何使用mgo包在Go中构建$ ifNull行?

我尝试过:

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

但它总是为news_count字段返回一个空字符串。

非常感谢任何帮助!

编辑[已解决]:

问题很愚蠢,我对Go "news_count": bson.M{ "$ifNull": [2]interface{}{"$news_count.count", 0}, } type字段的错误news_count

为了完整起见,Go中的管道是:

struct

结果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}, }, }, }, }

struct

1 个答案:

答案 0 :(得分:0)

您的news_count投影有效,错误位于您尚未发布的代码中的其他位置。

请参阅此完整的工作示例:

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())

输出:

map[_id:ObjectIdHex("592400188d84961b7f34b0cd") username:randomuser2 distance:227534.08191011765 news_count:14]

map[username:randomuser1 distance:266222.98643136176 news_count:0 _id:ObjectIdHex("592400188d84961b7f34b0ce")]