繁体   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