查找其数组字段至少包含给定数组的n个元素的文档 [英] Find documents whose array field contains at least n elements of a given array

查看:78
本文介绍了查找其数组字段至少包含给定数组的n个元素的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上就是标题所说的.

It is basically what the title says.

输入:myArray =单词数组

我有一个具有领域的模型 wordsCollection,它是一个数组字段.

I have an model that have field wordsCollection , which is an array field.

如何查找该模型的所有文档,其中wordsCollections至少具有n个元素myArray

How can I find all documents of that model whose wordsCollections has at least n elements of myArray

推荐答案

假设我们的收藏夹中包含以下文档:

Let say we have the following documents in our collection:

{ "_id" : ObjectId("5759658e654456bf4a014d01"), "a" : [ 1, 3, 9, 2, 9, 0 ] }
{ "_id" : ObjectId("5759658e654456bf4a014d02"), "a" : [ 0, 8, 1 ] }
{ "_id" : ObjectId("5759658e654456bf4a014d03"), "a" : [ 0, 8, 432, 9, 34, -3 ] }
{ "_id" : ObjectId("5759658e654456bf4a014d04"), "a" : [ 0, 0, 4, 3, 2, 7 ] }

以及以下输入数组和n = 2

var inputArray = [1, 3, 0];

我们可以使用聚合框架返回那些数组字段至少包含给定数组的n个元素的文档.

We can return those documents where the array field contains at least n elements of a given array using the aggregation framework.

$match 仅选择具有数组的文档长度大于或等于n.这样可以减少管道中需要处理的数据量.

The $match selects only those documents with the array's length greater or equals to n. This reduce the amount of data to be processed in down in the pipeline.

$redact 管道运算符使用逻辑条件处理使用 $cond 运算符和特殊操作 $$KEEP 可保留"逻辑条件为真或 $$PRUNE 可以丢弃"文档中的条件是错误的.

The $redact pipeline operator use a logical condition processing using the $cond operator and the special operations $$KEEP to "keep" the document where the logical condition is true or $$PRUNE to "discard" the document where the condition is false.

在我们的例子中,条件是 $gte 如果两个数组的交集的 $size ,则返回true ,我们使用 $setIntersection 运算符计算得出的值大于或等于2.

In our case, the condition is $gte which returns true if the $size of the intersection of the two arrays, which we compute using the $setIntersection operator is greater than or equal 2.

db.collection.aggregate(
    [ 
        { "$match": { "a.1": { "$exists": true } } }, 
        { "$redact": { 
            "$cond": [ 
                { "$gte": [ 
                    { "$size": { "$setIntersection": [ "$a", inputArray ] } }, 
                    2
                ]},
                "$$KEEP", 
                "$$PRUNE" 
            ]
        }}
    ]
)

产生:

{ "_id" : ObjectId("5759658e654456bf4a014d01"), "a" : [ 1, 3, 9, 2, 9, 0 ] }
{ "_id" : ObjectId("5759658e654456bf4a014d02"), "a" : [ 0, 8, 1 ] }
{ "_id" : ObjectId("5759658e654456bf4a014d04"), "a" : [ 0, 0, 4, 3, 2, 7 ] }

这篇关于查找其数组字段至少包含给定数组的n个元素的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆