1

I have the following data inside a mongoose collection:

{
  map: 'Sydney',
  Postcode: 2000,
  mapItems: [
    {
      team: 'NONE',
      teamIcon: 20,
      x: 0.6092914,
      y: 0.28168318,
      flags: 0
    },
    {
      team: 'Alpha',
      teamIcon: 33,
      x: 0.63026464,
      y: 0.41642973,
      flags: 0
    },
    {
      team: 'Bravo',
      teamIcon: 20,
      x: 0.63026464,
      y: 0.41642973,
      flags: 0
    },
    {
      team: 'Alpha',
      teamIcon: 20,
      x: 0.63026464,
      y: 0.41642973,
      flags: 0
    }

}

I'm trying to return just the mapItems that have the team as "Alpha" and teamIcon is 33 or 52.

dyDB
    .find({
      $or: [
        {
          "mapItems.teamIcon": 33,
        },
        {
          "mapItems.teamIcon": 52,
        },
      ],
      $and: [
        {
          "mapItems.teamId": "Alpha" },
        },
      ],
    })
    .then((data) => {
      for (const dyn of data) {
        console.log(dyn);
      }
    });

But it just returns everything and doesn't seem to filter it. I'm not sure what else to try. Can anyone give some pointers?

1 Answer 1

1

You have to use or inside and:

dyDB.find({
    mapItems: {
      $elemMatch: {
        $and: [
          { $or: [{ teamIcon: 52 }, { teamIcon: 33 }] },
          { team: "Alpha" },
        ],
      },
    },
  })
  .then((data) => {
    for (const dyn of data) {
      console.log(dyn);
    }
  });
Sign up to request clarification or add additional context in comments.

6 Comments

It is still returning everything, nothing is being filtered.
@Yesman, dot operator removed, can you check now
Now I am getting MongoServerError: unknown operator: $and
@Yesman, i fixed syntax, can you try now
"TypeError: conditional $and requires an array" is now coming up
|

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.