2
{
  "_id": {
    "$oid": "5f8f067ecf44854d4c3b5286"
  },
  "photo": "",
  "followers": [
    {
      "$oid": "5f8f26f8cf44854d4c3b528f"
    },
    {
      "$oid": "5f9f1984cf44854d4c3b5292"
    },
    {
      "$oid": "5f8f06c9cf44854d4c3b528e"
    },
    {
      "$oid": "604b1d0649a2052e912f9c3f"
    },
    {
      "$oid": "5f8f0688cf44854d4c3b5287"
    },
    {
      "$oid": "62371c3b8fabe53cf4386b1f"
    }
  ],
  "following": [
    {
      "$oid": "5f9f1984cf44854d4c3b5292"
    },
    {
      "$oid": "5f8f26f8cf44854d4c3b528f"
    },
    {
      "$oid": "5f8f06c9cf44854d4c3b528e"
    }
  ],
  "email": "[email protected]",
  "firstname": "John",
  "lastname": "Doe",
  "username": "JohnDoe01",
  "__v": 0
}

I am trying to get a list of followers from a specific user. I have a list of blocked users, so I need to exclude those users from the followers list. For eg:

let blockedUsers = ['5f8f26f8cf44854d4c3b528f', '5f9f1984cf44854d4c3b5292'];

FYI : followers also user objects

Let me know any further details needed. Thanks in advance.

1 Answer 1

2

You can use $filter to filter the follower (id) that is not in the blocked list.

While you perform the comparison, make sure:

Option 1: Value(s) in the blocked list cast to ObjectId

or

Option 2: Cast the follower to string

Must compare values with the same type.

db.collection.aggregate({
  $set: {
    followers: {
      $filter: {
        input: "$followers",
        cond: {
          $not: {
            $in: [
              {
                $toString: "$$this"  // Or "$$this._id" for user Object
              },
              [
                "5f8f26f8cf44854d4c3b528f",
                "5f9f1984cf44854d4c3b5292"
              ]
            ]
          }
        }
      }
    }
  }
})

Sample Mongo Playground

Sign up to request clarification or add additional context in comments.

1 Comment

I added a new question, please have a look and let me know if you can help. link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.