在聚合中组合匹配过滤器

Combining match filter in the aggregation

如果我有一个对象 Post 有两个属性

场景:文档总数为100,IsHomePage设置为true的为20 in total,其余(80 in total 文档)是 属性 IsTagged 设置为 true.

的文档

如何使用 IsHomePage 和 IsTagged 设置为 true 且限制为 50 的随机文档构建对 select 所有 20 个的查询?

您可以使用 $unionWith 来组合您的 2 个逻辑。

db.collection.aggregate([
  {
    "$match": {
      IsHomePage: true
    }
  },
  {
    "$unionWith": {
      "coll": "collection",
      "pipeline": [
        {
          "$match": {
            IsHomePage: {
              $ne: true
            },
            IsTagged: true
          }
        },
        {
          "$sample": {
            "size": 50
          }
        }
      ]
    }
  }
])

这里是Mongo playground供您参考。