mongodb - 在 mongodb 中跟进
问题描述
我正在尝试以更少的查询实现后续建议功能
我有 1 个名为 Followers 的文档,其中包含
_id | follower | following
1 | A | B
2 | B | C
3 | C | D
4 | D | A
我如何建议 D 跟进
而如果 D 已经在后面跟着 A,那么 D 不会出现在结果集中,因为你已经在跟着他了
_id | follower | following
1 | A | B
2 | B | C
3 | C | D
4 | D | A
5 | A | D
到目前为止我尝试过的查询是
let results = Follower.find({ following: userId }).select('follower').sort('-updatedAt').map(async user => {
let amIFollowingHim = await Follower.find({ follower: user.follower });
console.log(amIFollowingHim);
});
Actual snapshot of followers document in tabular format
[![Followers collection snapshot][1]][1]
[1]: https://i.stack.imgur.com/8se44.png
解决方案
试试下面的查询: -
const condition = {
$and: [
{ $or: [{ follower: mongoose.Types.ObjectId(userId) }, { following: mongoose.Types.ObjectId(userId) }] },
]
}
let data = await Follower.aggregate(
[
{ $match: condition },
{
$project: {
user: {
$cond: { if: { $eq: ["$follower", mongoose.Types.ObjectId(userId)] }, then: "$following", else: "$follower" }
},
_id: 1,
}
}
]
)
if(data){
const friend_id = data.map(friend => (mongoose.Types.ObjectId(friend.user)));
const index_id = data.map(friend => (mongoose.Types.ObjectId(friend._id)));
const condition = {
$and: [
{ '_id': { $nin: index_id } },
{ $or: [{ follower: { $in: friend_id } }, { following: { $in: friend_id } }] },
]
}
await Follower.aggregate(
[
{ $match: condition },
{
$project: {
user: {
$cond: { if: { $in: ["$follower", friend_id] }, then: "$following", else: "$follower" }
},
_id: 1
}
},
{
$lookup: {
from: "users",
let: { "id": "$user" },
pipeline: [
{ $match: { $expr: { $eq: ["$_id", "$$id"] } } }
],
as: "user"
}
},
{ $match: { "user._id": { $nin: friend_id } } },
{ $unwind: '$user' },
{ $group: { "_id": '$user._id', user: { $addToSet: '$user' } } },
{
$project: { _id: 1, user: { $arrayElemAt: ["$user", 0] } }
}
]
);
}
推荐阅读
- dataframe - pyspark withColumn,如何改变列名
- cmake - 如何在 CMake 中添加选项 `llvm-config --cxxflags --ldflags --libs`?
- javascript - 如何使用语言文件添加数据表按钮?
- tensorflow - model.fit 如何在 Keras 中工作?
- angular - Angular,如何对数组的翻译值进行排序
- db2 - 如何检查哪个 mln 处于写挂起模式
- angular - 用数据确定角度路线
- android - 调查问卷的自适应/可扩展 Recyclerview
- mysql - 无法在 mysql 工作台中添加外键约束,错误 1215。
- javascript - 使用 Jest 测试组件失败