Select documents where all values in an array field exist in another array

前端 未结 1 1291
时光取名叫无心
时光取名叫无心 2020-12-07 04:06

I wasn\'t quite sure how to title this!

So I have an array of product IDs

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

And a bunch of customer

相关标签:
1条回答
  • 2020-12-07 05:05

    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" 
            ] 
        }} 
    ])
    
    0 讨论(0)
提交回复
热议问题