mongoDB 查询以获取所有未被用户关注的用户

mongoDB query to get all users that are not followed by a user

我是 mongoDB 的新手,在编写查询时遇到了一些困难。

对于给定的用户,我需要找到他尚未关注的用户。

{
  _id:1,
  username:"user1",
  follows:[2,3]
},
{
  _id:2,
  username:"user2",
  follows:[3]
},
{
  _id:3,
  username:"user3",
  follows:[1]
},
{
  _id:4,
  username:"user4",
  follows:[2,1]
},
{
  _id:5,
  username:"user5",
  follows:[3]
}

请注意,follows 字段包含 _id 个特定用户正在关注的用户。 我需要编写一个查询,为我提供一个用户未关注的所有用户的列表。 就像用户 1 不关注用户 4 和用户 5

所以对于 user1,我的输出将是:-

{
  _id:4,
  username:"user4",
  follows:[2,1]
},
{
  _id:5,
  username:"user5",
  follows:[3]
}

您必须检索给定用户的 follows 字段并像这样使用 $nin

const userId = 1;

const { follows } = await User.findById(userId);
follows.push(userId); // also exclude user 1

const users_list = await User.find({ _id: { $nin: follows } });
db.collection.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $unwind: {
                path: "$follows",
                preserveNullAndEmptyArrays: false // optional
            }
        },

        // Stage 2
        {
            $group: {
                _id: null,
                user_ids: {
                    $addToSet: '$_id'
                },
                follows: {
                    $addToSet: '$follows'
                },
                doc: {
                    $push: '$$ROOT'
                }


            }
        },

        // Stage 3
        {
            $project: {
                doc: 1,
                notfollowed: {
                    $setDifference: ["$user_ids", "$follows"]
                }
            }
        },

    ]



);