选择其中一个数组字段中的所有值都存在于另一个数组中的文档 [英] Select documents where all values in an array field exist in another array

查看:96
本文介绍了选择其中一个数组字段中的所有值都存在于另一个数组中的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太确定该如何命名!

I wasn't quite sure how to title this!

所以我有一系列的产品ID

So I have an array of product IDs

var productIds = [139,72,73,1,6]

以及MongoDB中的一堆客户文档

And a bunch of customer documents in MongoDB

{
    name: 'James',
    products: [ 73, 139 ],
    _id: 5741cff3f08e992598d0a39b
}

{
    name: 'John',
    products: [ 72, 99 ],
    _id: 5741d047f08e992598d0a39e
}

当他们的所有产品都出现在产品ID(产品ID)数组中时,我想找到客户

I would like to find customers when all of their products appear in the array of product IDs (productIds)

我尝试过:

'products' : {
    '$in': productIds
}

但是,即使产品ID列表中不存在99,这也将返回John

But that returns John, even though 99 doesn't exist in the list of product IDs

我也尝试过:

'products' : {
    '$all': productIds
}

由于没有一个客户拥有所有产品,因此什么也不退货

Which returns nothing because none of the customer have ALL the products

是否有一种方法可以在单个查询中实现我所需要的?还是必须进行一些后查询处理?

Is there a way to achieve what I need in a single query or am I going to have to do some post query processing?

我也尝试过

'products': {
    '$in': productIds,
    '$not': {
        '$nin': productIds
    }
}

但是,当并非所有产品ID都匹配时,这似乎还会吸引客户

but this also seems to return customers when not all product IDs match

推荐答案

您可以使用 $cond 表达式中,您需要使用 $setIsSubset 以便检查是否产品"数组位于"productIds"中.这是因为您不能在条件条件下使用 $in 表达式

You can do this using the .aggregate() method and the $redact operator. In your $cond expressions you need to use the $setIsSubset in order to check if all the elements in the "products" array are in "productIds". This is because you cannot use $in in the conditional expression

var productIds = [139,72,73,1,6];
db.customers.aggregate([ 
    { "$redact": { 
        "$cond": [ 
            { "$setIsSubset": [ "$products", productIds ] },
            "$$KEEP",
            "$$PRUNE" 
        ] 
    }} 
])

这篇关于选择其中一个数组字段中的所有值都存在于另一个数组中的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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