KevinVuD
KevinVuD

Reputation: 611

Followers - mongodb query check

I have 2 collections in my database. One is called User

{
   _id: storeUserId,
   name: ...,
   etc
}

the other one called Following

{
   userId: ...,
   followingUserId: ...
}

the userId is the current user id and the followingUserId is the id that current user wants to follow.

For example, in User collection I have:

{
  _id: userIdOne,
   etc
},
{
  _id: userIdTwo,
  etc
}

and in Following collection I have:

{
  userId: userIdThousand,
  followingUserId: userIdTwo
}

When I run find query

db.bios.find();

I get

   {
    "_id": userIdTwo,
    "username": "random27005688"
},
{
    "_id": userIdThree
    "username": "random232111"
},
{
    "_id": userIdOne
    "username": "random2702"
}
]

The result is what I want but I want to add a 'isFollowed' field to each result item to check following status. I have a user id let say: 'userIdThousand' which I want to use it to check against each result item based on my Following collection. E.g,

check if userIdThousand is following userIdOne
check if userIdThousand is following userIdTwo, etc.

Below is my expected result. Thanks!

[
{
    _id: userIdTwo,
    "username": "random27005688",
    "isFollowed": true
},
{
    "_id": userIdThree
    "username": "random232111",
    "isFollowed": false
},
   {
    "_id": userIdOne
    "username": "random2702",
     "isFollowed": false
},
]

Upvotes: 0

Views: 699

Answers (2)

fang jinxu
fang jinxu

Reputation: 325

maybe you could split it into two step.

1. query User and get the result

for example, you get a user.

{
    _id: userIdTwo,
    "username": "random27005688",
}

2. query Following and get if the user has been followed.

such as

has_followed=db.Following.find({"userId":userIdTwo}).count()

not the best solution but it might help u.

Upvotes: 0

mickl
mickl

Reputation: 49985

You need $lookup to get the data from second collection matching by followingUserId then you can use $filter to get only followers with particular _id and check if new array has any elements (using $size) which means that user is followed by other user:

db.User.aggregate([
    {
        $match: {
            _id: { $ne: "userIdOne" }
        }
    },
    {
        $lookup: {
            from: "Following",
            localField: "_id",
            foreignField: "followingUserId",
            as: "followers"
        }
    },
    {
        $addFields: {
            followers: {
                $filter: { input: "$followers", as: "follower", cond: { $eq: [ "$$follower._id", "userIdOne" ] } }
            }
        }
    },
    {
        $project: {
            _id: 1,
            username: 1,
            isFollowed: { $gt: [ { $size: "$followers" }, 0 ] }
        }
    }
])

Upvotes: 1

Related Questions