Home > Blockchain >  MongoDB $nin $elemMatch behaviour
MongoDB $nin $elemMatch behaviour

Time:01-14

When trying to do a $nin match with $elemMatch in .net I get no results. I've reconstructed the statement on Mongo Playground.

I guess I'm missing something around the $nin but can't find anything in the docs.

This post is talking about the issue but the solution they gave doesn't work if you set the data up with a valid exclude.

I've read through the docs and a few posts around this issue, I'm assuming there is a gap in my knowledge around how $nin and or $elemMatch works, I hope someone can point me in the correct direction and possible fix the example on mongo playground.

CodePudding user response:

You are mistaking the behaviour of $elemMatch. $elemMatch will return the document if any of the array element match your criteria.

For your expected behaviour, you can simply do:

db.collection.aggregate([
  {
    $match: {
      "ingredient.name": {
        $nin: [
          "X"
        ]
      }
    }
  }
])

Mongo Playground

  • Related