我是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);
const users_list = await User.find({ _id: { $nin: follows } });