Search code examples
pythondatabasemongodbnosqlpymongo

How can I get only a single value back in MongoDB (Pymongo)


This is the document I have right now:

{
    _id: ObjectId("62464e3e75c6d843a338993b"),
    Name: 'The Team',
    Members: [
      { User: Long("699724278526580847"), Rank: 3 },
      { User: Long("937398909418999808"), Rank: 4 },
      { User: Long("829765893287562113"), Rank: 1 },
      { User: Long("090119389582045756"), Rank: 1 },
      { User: Long("772474927459011034"), Rank: 1 },
    ]
}

I want to get the "Rank" Value of a user which is chosen through an input, for this example let's say the person executing the command chose the user with the ID "699724278526580847", how would I query and get just the rank of that user returned? Is it possible in pymongo to just get the integer value of that user's rank?


Solution

  • Maybe something like this in mongo that you can convert easily to python:

    db.collection.aggregate([
     {
      $match: {
         Name: "The Team" , "Members.User": NumberLong("699724278526580847")
      }
     },
    {
    "$addFields": {
      "Members": {
        "$filter": {
          "input": "$Members",
          "as": "m",
          "cond": {
            $eq: [
              "$$m.User",
              NumberLong("699724278526580847")
            ]
          }
        }
       }
      }
      },
      {
       $unwind: "$Members"
      },
      {
       "$project": {
         Rank: "$Members.Rank",
         _id: 0
      }
     }
    ])
    

    Explained:

    1. Match the Member & The Team
    2. Filter only the Member by User from the array
    3. Unwind the array to convert to object
    4. Project only the Rank field

    playground