[英]MongoDB match documents with all elements in a given array
I have an array 我有一个数组
solvedProblemIds = [0,2]
and I want to query for documents that have ALL of the elements in their requiredProblems array inside the solvedProblemIds array. 我想查询在solvedProblemIds数组内的requiredProblems数组中具有所有元素的文档。
for example, if these are my documents: 例如,如果这些是我的文档:
{
id: 0,
name: "Problem 1",
points: 10,
description: "Problem 1 desc",
requiredProblems: []
},
{
id: 1,
name: "Problem 2",
points: 10,
description: "Problem 2 desc",
requiredProblems: [0]
},
{
id: 2,
name: "Problem 3",
points: 10,
description: "Problem 3 desc",
requiredProblems: [0]
},
{
id: 3,
name: "Problem 4",
points: 10,
description: "Problem 4 desc",
requiredProblems: [0, 2]
},
{
id: 4,
name: "Problem 5",
points: 10,
description: "Problem 5 desc",
requiredProblems: [0, 1, 2, 3]
}
The query should match the documents with id 3, 2, 1, and 0. I looked at the $in selector, but it only requires ONE element to be in the array, not all. 该查询应与ID为3、2、1和0的文档匹配。我查看了$ in选择器,但它只要求在数组中包含一个元素,而不是全部。
There's no operator that works out of the box for determining a subset. 没有开箱即用的运算符来确定子集。 You can either do an aggregation (I haven't thought about how) or the following: 您可以进行汇总(我还没考虑过如何)或执行以下操作:
{ $not: { $elemMatch: { $nin: [0, 2] } } }
This is finding documents such that there exists no elements that are not in [0, 2]. 这是在查找文档,使得不存在[0,2]中没有的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.