Search code examples
pythonmongodbpymongo

How can I limit output of MongoDB query in Python?


I have this example MongoDB entry in a users DB:

{
     _id: xxx,
     name: "name",
     files:[{
          fileName: "test",
          size: 654
          },
          {fileName: "test2",
          size: 50
     }]
}

And I'm using Pymongo to query the file named "test":

users.find_one({'files.filename':"test"})

How can I limit the output from Pymongo, so it only gives me the dict where "test" is contained? In other words, I want it to output this:

{
     fileName: "test",
     size: 654
}

Solution

  • Here's one way you could do it.

    db.users.aggregate([
      {
        "$match": {
          "files.fileName": "test"
        }
      },
      {
        "$replaceWith": {
          "$first": {
            "$filter": {
              "input": "$files",
              "as": "file",
              "cond": {
                "$eq": ["$$file.fileName", "test"]
              }
            }
          }
        }
      }
    ])
    

    Try it on mongoplayground.net.