在单个聚合查询中组合多个 $samples mongodb

Combining multiple $samples in single aggregate query mongodb

我正在处理一个查询,使用条件和样本大小

从 mongodb 检索样本文档
db.getCollection('questionBank').aggregate(
   [{"$match":{"difficultyLevel":"Intermediate"}}, { $sample: { size: 5 } } 
   ]
)

db.getCollection('questionBank').aggregate(
       [{"$match":{"difficultyLevel":"Low"}}, { $sample: { size: 3 } } 
       ]
    )


db.getCollection('questionBank').aggregate(
           [{"$match":{"difficultyLevel":"High"}}, { $sample: { size: 2 } } 
           ]
        )

我想从问题库中获取一组难度级别为中级,5 低,3 和高,2 的记录 我能够使用三个单独的聚合查询获取所有这些记录,并将 3 个查询结果合并到一个数组中。

有没有办法在单个查询中完成此操作

有。 $facet$project 会为你做到这一点:

db.collection.aggregate([
  {
    "$facet": {
      "Intermediate": [
        {
          "$match": {
            "difficultyLevel": "Intermediate"
          }
        },
        {
          $sample: {
            size: 3
          }
        }
      ],
      "Low": [
        {
          "$match": {
            "difficultyLevel": "Low"
          }
        },
        {
          $sample: {
            size: 2
          }
        }
      ],
      "High": [
        {
          "$match": {
            "difficultyLevel": "High"
          }
        },
        {
          $sample: {
            size: 1
          }
        }
      ]
    }
  },
  {
    "$project": {
      merged_results: {
        $concatArrays: [
          "$Intermediate",
          "$Low",
          "$High"
        ]
      }
    }
  }
])

游乐场:https://mongoplayground.net/p/h981En8lJBo