查找数组包含超过X条记录的记录

Finding records where arrays contain more than X records?

本文关键字:记录 数组 包含超 查找      更新时间:2023-09-26

我有一个集合,其中包含如下结构的文档:

{
   "title": "some title",
   "participants": [1,2,3],
   "questions": ["question1", "question2", "question3"]
}

我想写一个查询,允许我选择在participants数组中有超过4个元素的所有文档在questions数组中有超过3个元素。我可以运行以下查询:

db.myCollection.find({
        "$where": "this.questions.length > 3", 
        "$where": "this.participants.length > 4"}
).pretty()

但它只应用最后一个$where条件(因此只有1个问题的文档仍然被返回)。我如何根据数组长度应用多个条件到我的查询?

您可以使用点符号来检查是否存在特定的索引,例如:

db.myCollection.find({
        "questions.3" : {$exists : true}, 
        "participants.4" : {$exists : true}}
)

相当于"查找questions.size()> 3和participants.size()> 4的文档"。

此方法由JohnyHK here(第二个答案)

建议。