簡體   English   中英

MongoDB - 查找嵌套文檔列表具有多個值大於 0 的字段

[英]MongoDB - Find where list of nested documents has more than one field with a value greater than 0

我有一組具有以下形狀的User文檔:

// User

{
  payments: [
    { total: number }, 
  ],
}

可變長度嵌套文檔的payments數組包含值等於或大於 0 的totals

如何找到total > 0payments長度大於 1 的Users列表?

例如,我想找到這樣的文件:

// two totals > 0 👍
{
  payments: [
    { total: 50 }, 
    { total: 50 },
  ],
}
// two totals > 0 👍
{
  payments: [
    { total: 50 },
    { total: 0 },
    { total: 50 },
  ],
}
// three totals > 0 👍
{
  payments: [
    { total: 50 },
    { total: 50 }, 
    { total: 0 }, 
    { total: 50 }, 
  ],
}

但不是這些文件:

// not enough totals > 0 👎
{
  payments: [
    { total: 50 }, 
    { total: 0 },
    { total: 0 }, 
  ],
}
// not enough totals > 0 👎
{
  payments: [
    { total: 0 },
    { total: 0 }, 
  ],
}

感謝您提前提供任何幫助!

演示 - https://mongoplayground.net/p/AG8Q1GqSEcl

您必須使用聚合查詢。

$filter數組,其中總和大於 0 並獲取過濾數組的$size 檢查它是否大於 1 $match

$項目

db.collection.aggregate([
  {
    $project: {
      payments: "$payments",
      paymentsGreaterThanZero: {
        $size: {
          $filter: { input: "$payments", as: "item", cond: { $gt: [ "$$item.total",0 ] } }
        }
      }
    }
  },
  { $match: { paymentsGreaterThanZero: { $gt: 1 } } },
  { $project: { payments: "$payments" } }
])

暫無
暫無

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

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