db.followers.aggregate([ {$match: { fserid: ObjectId("56b329fa2620e5438555992a")} }, {$lookup: { from: "users", localField: "fuserid", foreignField: "_id", as: "postcode_docs"} } ]);
How can we write similar query in Go (mgo) :
Hi Vineet,
Below is a sample code that runs aggregation using $match and $lookup based on your query:
collection := session.DB("test").C("followers")
pipeline := []bson.M{
bson.M{"$match":
bson.M{"fuserid": bson.ObjectIdHex("56b329fa2620e5438555992a")}},
bson.M{"$lookup":
bson.M{ "from": "users", "localField": "fuserid", "foreignField": "_id", "as": "postcode_docs"}},
}
pipe := collection.Pipe(pipeline)
resp := []bson.M{}
err = pipe.All(&resp)
The snippet above was tested on Golang v1.5.3, gopkg.in/mgo.v2, and MongoDB v3.2.1
I tried this but it throws tons of errors :
If you are still having issues, it would be useful to post the actual errors you are getting.
Best regards,
Wan
interface conversion: interface is bson.ObjectId, not string
My query works fine in a terminal (or Robomongo) but not in mgo. Both localField and foreignField are ObjectId’s then am I correct in understanding mgo requires a string?
Hi Ron,
Both the localField
and foreignField
are field names (string) from documents, not an ObjectId()
. See also $lookup for more description.
You can also utilise the sample mgo $lookup
listed previously in this thread as a start.
If you still have any questions, could you provide the following :
Regards,
Wan.