Alex Zhukovskiy
Alex Zhukovskiy

Reputation: 10015

MongoDb $elemMatch is not working as expected

I'm writing a simple query that's using objects with propery Tags and has to return a document if following is true:

  1. It has exactly 3 items
  2. One of them is :image
  3. One of them starts with : but is not an image
  4. One of them doesn't start with :

So I want records of type { Tags : [":image", ":ianything", "somethingelse"] }

I write following:

db.myCollection.find({
  Tags: {
    $elemMatch: {
      $eq: ":image"
    },
    $elemMatch: {
      $ne: ":image",
      $regex: /^:\w+$/
    },
    $elemMatch: {
      $regex: /^\w+$/
    },
    $size: 3
  }
}).limit(50)

But it doesn't work as expected and return items like { Tags : [":image", "something", "somethingelse"] }

Where am I mistaken?

Upvotes: 0

Views: 690

Answers (1)

Alex Blex
Alex Blex

Reputation: 37028

You need to use $and to combine conditions:

db.myCollection.find({ $and: [
  { Tags: {
    $elemMatch: {
      $eq: ":image"
  } } },
  { Tags: {
    $elemMatch: {
      $ne: ":image",
      $regex: /^:\w+$/
  } } },
  { Tags: {
    $elemMatch: {
      $regex: /^\w+$/
  } } },
  { Tags: { $size: 3 } }
] });

Upvotes: 1

Related Questions