0

My collection schema is as follows:

Product

{
  _id: ObjectId(), // default mongo db id
  specification: [
    {key: 'Name', value: "value 1"},
    {key: 'Category', value: "value 2"},
    {key: 'Department', value: "value 3"}
  ]
}

Now I want to query on this with a generic filter. For example,

  1. Get me all product with Name = value 1 and Category in [value 2, value 3] and Department = value 3
  2. Get me all product with Name = value 1 or Category = value 2 or Department in [value 3, value 4]

I have been trying to use $match with $elemMatch. But that only allows only one query but I am not able to use the $and and $or operator.

1
  • so you want two queries? one for Get me all product with Name = value 1 and Category in [value 2, value 3] and Department = value 3 And other for Get me all product with Name = value 1 or Category = value 2 or Department in [value 3, value 4] Commented May 5, 2020 at 18:33

1 Answer 1

0

You can use $elemMatch just fine, you just have to put $and / $or at the top level.

Your first example would be

db.products.find({
  $and: [
    { 
      specification: {
        $elemMatch: { key: 'Name', value: 'value 1' }
      }
    },
    {
      specification: {
        $elemMatch: { key: 'Category', value: { $in: ['value 1', 'value 2'] } }
      }
    },
    { 
      specification: {
        $elemMatch: { key: 'Department', value: 'value 3' }
      }
    }
  ]
})
Sign up to request clarification or add additional context in comments.

Comments

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.