【问题标题】:Mongodb How to filter a Document as not to pass fields with empty in the next stage in pipeline in Aggregation framework [duplicate]Mongodb如何过滤文档以在聚合框架的管道的下一阶段不传递空字段[重复]
【发布时间】:2020-05-28 09:37:53
【问题描述】:

我有这样的文件:

{
 _id:'5e2b8a2065318f95166deedc'
 expenses:[{amount:100},{amount:200}]
},
{
 _id:'5e2b8a2065318f95166deedc'
 expenses:[]
},
{
 _id:'5e2b8a2065318f95166deedc'
 expenses:[{amount:400},{amount:600}]
}

我需要用聚合查询返回 WITH EXPENSES 字段,即空数组的费用不应该返回到管道的下一步

这是我迄今为止尝试过的:

Exps.aggregate([

    {$match: {"id":ObjectId(myId)}},

    {$group:{
        _id:'$_id',
        expenses:{$last:"$expenses"},
    }}
   ])

但这会返回所有三个子文档,包括空的。我怎样才能获得第一个和第三个子文档(根据我的示例),以便我可以将它们传递给管道的下一步?

【问题讨论】:

标签: mongodb express aggregation-framework


【解决方案1】:

如果expenses 有一个或多个条目,则expenses.1 将存在。因此,以下将起作用。

db.collection.aggregate([
  {
    $match: {
      "expenses.1": {
        $exists: true
      }
    }
  }
])

https://mongoplayground.net/p/Hkti0Fj8U3I

或将sizenot 一起使用

db.collection.aggregate([
  {
    $match: {
      "expenses": {
        $not: {
          $size: 0
        }
      }
    }
  }
])

https://mongoplayground.net/p/EpYDtEBf0yk

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-03
  • 2020-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多