首页 > 解决方案 > 在 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

标签: mongodbmongoosemongodb-query

解决方案


试试下面的查询: -

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] } }
            }
        ]
    );
}

推荐阅读