【问题标题】:mongoDB query to get all users that are not followed by a usermongoDB查询以获取用户未关注的所有用户
【发布时间】:2020-03-28 01:10:15
【问题描述】:

我是 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]
}

【问题讨论】:

    标签: mongodb mongoose mongodb-query mongodb-atlas


    【解决方案1】:

    您必须检索给定用户的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 } });
    

    【讨论】:

    • 尽管它也在用户结果列表中显示当前用户,但没关系我会过滤掉它..非常感谢:-)
    【解决方案2】:
    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"]
                    }
                }
            },
    
        ]
    
    
    
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-08
      • 1970-01-01
      • 2015-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多