Node.js 在猫鼬中获得共同的追随者
我希望获得相互的(因此,从所有用户中,我拥有最多的共享关注者的用户(我们都关注同一个用户)按该计数排序)。具有聚合功能的my database scheme(mongoDB)的追随者 用户方案:Node.js 在猫鼬中获得共同的追随者,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我希望获得相互的(因此,从所有用户中,我拥有最多的共享关注者的用户(我们都关注同一个用户)按该计数排序)。具有聚合功能的my database scheme(mongoDB)的追随者 用户方案: let User = new mongoose.Schema({ uid: { type: String, require: true, unique: true }, followers: [String], following: [String] }) 其中
let User = new mongoose.Schema({
uid: {
type: String,
require: true,
unique: true
},
followers: [String],
following: [String]
})
其中followers/following是UID的数组
我试过这个:
let me = await User.findOne({uid: uid})
if (me) {
console.log(me.followers)
let mutual = await User.aggregate([
// Match documents that contain the elements
{ "$match": {
"followers": { "$in": me.followers }
}},
// // De-normalize the array field content
{ "$unwind": "$followers" },
// Match just the elements you want
{ "$match": {
"followers": { "$in": me.followers }
}},
// Count by the element as a key
{ "$group": {
"_id": "$name",
"mutual": { "$sum": 1}
}}
])
if (mutual) {
console.log('mutual', mutual)
}
}
但这并不能给出正确的计数您可以使用
$filter
和$size
而不是为每个人展开追随者。您还可以使用$lookup
而不是2个客户端查询来完成此操作
以下管道中的阶段:
- $匹配有问题的用户
- $lookup检索具有公共跟随者的所有使用,将它们放置在
匹配的
数组中
- $match-由于所讨论的用户也会被匹配为具有匹配的跟随者,因此消除此“自我”条目
- $project删除除其他人的
之外的所有字段,对于普通追随者:uid
- $filter迭代每个persons
array,只保留与相关用户匹配的条目followers
- $size返回剩余的元素数
- $filter迭代每个persons
看起来该查询将找到所有跟随原始
uid
的人。所谓“共同追随者”,你的意思是你想找到所有跟随uid
的人,他们uid
也跟着你吗?或者,您是否正在寻找同样跟随uid
的人?问题不完整。你能定义一下你所说的“共同”是什么意思吗?先生,你是一个传奇!
[
{"$match": {"uid": uid}},
{
"$lookup": {
"from": "User",
"localField": "followers",
"foreignField": "followers",
"as": "matched"
}},
{"$unwind": "$matched"},
{"$match": {"$expr": {"$ne": ["$matched.uid", "$uid"]}}},
{"$project": {
"_id": 0,
"uid": "$matched.uid",
"commonFollowers": {
"$size": {
"$filter": {
"input": "$matched.followers",
"cond": {
"$in": [
"$$this",
"$followers"
]
}}}}}},
{"$sort": {"commonFollowers": -1}}
])