简体   繁体   English

MongoDB将文档与给定数组中的所有元素匹配

[英]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.

相关问题 使用包含(子)文档数组的文档查询MongoDB集合,其中该数组中的所有文档均与条件匹配 - Querying a MongoDB collection with documents containing an array of (sub)documents where ALL documents in the array match a condition 所有元素均符合条件的MongoDB查询数组 - MongoDB query array where all elements match criteria Mongodb:查找具有数组的文档,其中所有元素都存在于查询数组中,但是文档数组可以更小 - Mongodb: find documents with array where all elements exist in query array, but document array can be smaller 如何在mongoDB中的数组和文档之间进行匹配和查找 - How to match and find between an array and documents in mongoDB Mongo过滤/查找嵌入式数组中匹配条件并返回周围文档的所有元素? - Mongo filter/find all elements in embedded array that match a criteria and return surrounding documents? MongoDB - 将集合的 id 与给定的数组匹配 - MongoDB - match id of a collection with the given array MongoDB数组查询以返回与数组中大多数元素匹配的文档 - MongoDB Array Query to return documents that matches Most elements in array 如何匹配 MongoDB 中元素数组中的字符串 - How to match a String in array of elements in MongoDB 如何在mongoDB中查找具有所有指定数组值的所有文档? - How to find all documents with all specified array values in it in mongoDB? MongoDB:如何查询一系列文档/词典中的元素数量? - MongoDB: How do I query for the number of elements in an array of documents/dictionaries?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM