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