1

basically I'm trying to create a boolean field "focus" in a query that is true if a field "focusStores" contains a certain store.

Example: If a product as the following focus stores - ["AAA","BBB"] and if I'm using the store "AAA" as a search criteria the focus field should be true.

This is currently my best try. Any help would be appreciated!

   db.getCollection('Products').aggregate([
      {
        $project: {
          sku:  1,
          focusStores : 1,
          focusTmp : {$focusStores: {$in : 'AAA'}}
        }
      }
    ])
1
  • You can use $cond e.g. focusTmp : { $cond: { if: {$focusStores: {$in : 'AAA'}}, then: true, else: false } } Commented Oct 23, 2017 at 13:15

1 Answer 1

4

For MongoDB 3.2 use $setIsSubset:

   db.getCollection('Products').aggregate([
      {
        $project: {
          sku:  1,
          focusStores : 1,
          focusTmp : { $setIsSubset: [ ["AAA"], { "$ifNull": [ "$focusStores", [] } ] }
        }
      }
    ])

You probably read $in which is a MongoDB 3.4 operator, and got the syntax incorrect. Should be :

   db.getCollection('Products').aggregate([
      {
        $project: {
          sku:  1,
          focusStores : 1,
          focusTmp : { $in: [ "AAA", { "$ifNull": [ "$focusStores", [] ] } ] }
        }
      }
    ])

But only when you have a supporting version of course.

In both cases you wrap with $ifNull to cater for missing properties.

Sign up to request clarification or add additional context in comments.

3 Comments

I'm getting this error when trying the $setIsSubset "both operands of $setIsSubset must be arrays. Second argument is of type: EOO"
@MMrj Does your question not state that focusStores is an array of ["AAA","BBB"]? Because if it's not an array then that property is the one that needs wrapping in []. If neither are arrays then you just want $eq. But I'm reading your question as if it were an array, since that's the question you appear to be asking.
yes, the field should be an array but there are some cases where its null, maybe thats the problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.