Home > Software design >  Filter array in MongoDB aggregate with another array
Filter array in MongoDB aggregate with another array

Time:04-05

{
  "_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 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.

CodePudding user response:

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

  • Related