Home > Enterprise >  Check if 2 Users are in the same array and compare their ranks in MongoDB (Pymongo)
Check if 2 Users are in the same array and compare their ranks in MongoDB (Pymongo)

Time:04-02

I'm having difficulties with a specific task in Python and MongoDB. Firstly, I have some user data stored as objects in a MongoDB Array, and the first thing I need to do is check to see if 2 users are in the same array. If they are, I need to check if one user's rank is higher than the other's. If the user's rank is higher, then he is allowed to kick the other user. Otherwise, the user is told that he needs to have a higher rank than the targeted user. In this example there are only 2 users, but in reality there are many many users and 2 are selected based off a sent command in discord, so I can't just do array[0], array[1]. The data is stored like this:

  

    {
        _id: ObjectId("62464e3e75c6d843a338993b"),
        Name: 'Team',
        Members: [ 
            { 
                User: Long("699724378526580848"), 
                Rank: 4 
            } 
        ]
    }

If it's possible to check if the users are both in the same array using just one query, that would be great. If not, then whatever is the most efficient way will work.

CodePudding user response:

Use $all

db.collection.aggregate([
  {
    $match: { "Members.User": { $all: [ 123, 456 ] } }
  },
  {
    $unwind: "$Members"
  },
  {
    $sort: { "Members.Rank": -1 }
  },
  {
    $limit: 1
  }
])

mongoplayground

  • Related