Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb find with opposite of $elemMatch

I have a collection like this:

posts = {
  title: 'Hey',
  content: '...',
  authors: [{
    id: 'id',
    name: 'John'
  }, {
    id: 'id2',
    name: 'david'
  }]
};

I want to make a query. I have found the $elementMatch, but I would like the opposite.

I have also found $nin but I don't if it works for mycase.

Here is what I want to do:

db.posts.find({
  authors: {
    $notElemMatch: {
      id: 'id'
    }
  }
});

I want to find every posts except those writing by someone.

like image 960
BoumTAC Avatar asked Sep 16 '25 02:09

BoumTAC


1 Answers

You don't even need $elemMatch since you only have a single field condition. Just use $ne instead:

db.posts.find({ "authors.id": { "$ne": 'id' } });

There is a $not condition, but it really does not need apply here.

like image 141
Blakes Seven Avatar answered Sep 17 '25 15:09

Blakes Seven