Home > database >  Sort Mongodb documents by seeing if the _id is in another array
Sort Mongodb documents by seeing if the _id is in another array

Time:10-25

I have two collections - "users" and "follows". "Follows" simply contains documents with a "follower" field and a "followee" field that represent when a user follows another user. What I want to do is to be able to query the users but display the users that I (or whatever user is making the request) follow first. For example if I follow users "5" and "14", when I search the list of users, I want users "5" and "14" to be at the top of the list, followed by the rest of the users in the database.

If I were to first query all the users that I follow from the "Follows" collection and get an array of those userIDs, is there a way that I can sort by using something like {$in: [userIDs]}? I don't want to filter out the users that I do not follow, I simply want to sort the list by showing the users that I do follow first.

I am using nodejs and mongoose for this. Any help would be greatly appreciated. Thank you!

CodePudding user response:

Answer

db.users.aggregate([
  {
    $addFields: {
      sortBy: {
        $cond: {
          if: {
            $in: [ "$_id", [ 5, 14 ] ]
          },
          then: 0,
          else: 1
        }
      }
    }
  },
  {
    $sort: {
      sortBy: 1
    }
  },
  {
    $unset: "sortBy"
  }
])

Test Here

If you don't want you on the list, then

db.users.aggregate([
  {
    $addFields: {
      sortBy: {
        $cond: {
          if: {
            $in: [ "$_id", [ 5, 14 ] ]
          },
          then: 0,
          else: 1
        }
      }
    }
  },
  {
    $sort: {
      sortBy: 1
    }
  },
  {
    $unset: "sortBy"
  },
  {
    $match: {
      "_id": { $ne: 1 }
    }
  }
])

Test Here

If you want to sort users first

db.users.aggregate([
  {
    $sort: {
      _id: 1
    }
  },
  {
    $addFields: {
      sortBy: {
        $cond: {
          if: {
            $in: [
              "$_id",
              [
                5,
                14
              ]
            ]
          },
          then: 0,
          else: 1
        }
      }
    }
  },
  {
    $sort: {
      sortBy: 1,
      
    }
  },
  {
    $unset: "sortBy"
  },
  {
    $match: {
      "_id": {
        $ne: 1
      }
    }
  }
])

Test Here

  • Related