MongoDB $ifNull 条件与 mgo

MongoDB $ifNull conditional with mgo

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

样本数据'users'合集:

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

样本数据'newscounter'合集:

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

mongo 中的查询如下所示:

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

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

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

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

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

我试过:

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

但它 returns 始终是 news_count 字段的空字符串。

非常感谢任何帮助!

编辑[已解决]:

这个问题很愚蠢,我在 Go structnews_count 字段的 type 错误

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

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

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"`
      }

您的 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")]