簡體   English   中英

如何在 Python 中限制 MongoDB 查詢的 output?

[英]How can I limit output of MongoDB query in Python?

我在users數據庫中有這個示例 MongoDB 條目:

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

我正在使用 Pymongo 查詢名為“test”的文件:

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

如何限制 Pymongo 的 output ,所以它只給我包含“測試”的dict 換句話說,我想要它 output 這個:

{
     fileName: "test",
     size: 654
}

這是您可以做到的一種方法。

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

mongoplayground.net上試試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM