我分三步解决/修复了它(用ruby/mongoid编写):
//get users the user X follows
users = Follow.collection.aggregate([
{ "$match": { "followable_id": BSON::ObjectId.from_string(userid) } },
{ "$lookup": { from: "users", localField: "user_id", foreignField: "_id", as: "user" } },
{ "$unwind": "$user" },
{ "$sort": {"created_at":-1} },
{ "$skip": page * 10 },
{ "$limit": 10 },
{ "$group":{ _id: "$followable_id", data: {"$addToSet": "$user._id"} } }
])
userids=users.blank? ? [] : users.first['data'].to_a
//get users I follow
f=Follow.collection.aggregate([
{"$match":{user_id: BSON::ObjectId.from_string(meid), followable_id: {"$in":userids}}},
{"$group":{ _id: nil, data: {"$addToSet": "$followable_id"}}}
])
//make intersection
users = User.collection.aggregate([
{ "$lookup": { from: "follows", localField: "_id", foreignField: "user_id", as: "follow" } },
{ "$unwind": "$follow" },
{ "$match": { "follow.followable_type": "User","follow.followable_id": BSON::ObjectId.from_string(userid) } },
{ "$group":{ _id: "$_id", data:{"$addToSet": "$$ROOT"}} },
{ "$unwind": "$data" },
{ "$project": {
_id: 1,data: 1,count: 1,
follow: {
'$cond': {
"if": { '$in': [ "$_id", f.first['data'] ] }, "then": true,
"else": false
}
}
}
},
{ "$skip": page * 10 },
{ "$limit": 10 }
])
输出:
name: Fausto Torres; Do I follow too? false; Counter that's make the magic: 1
name: kah; Do I follow too? false; Counter that's make the magic: 1
name: Marianno; Do I follow too? true; Counter that's make the magic: 2
name: Diego_Lukmiller; Do I follow too? true; Counter that's make the magic: 2
查询执行得很快,看起来很简单。
有没有办法/如何在一个查询中解决它?!?