6

In Mongoose, if a model M has this field:

list: {type:[String]}

How should I find a document in which a specific value x is not an element of 'list'? I am hoping there is a special operator '$ncontains' so that I can do the following:

M.findOne({list:{$ncontains:x}}...
Chong Lip Phang
  • 8,755
  • 5
  • 65
  • 100
  • For a "singular" value to match, MongoDB does not care if the data is in an array or not. Usually `$ne` will do. If you have a "list" of values you want to be "not" for either an array or a single value field, then use `$nin` – Neil Lunn May 20 '18 at 08:44
  • Wrote this many years ago. And people still get it wrong. [To $nin or not to $nin](https://snakierten96.wordpress.com/2014/12/08/to-nin-or-not-to-nin/) – Neil Lunn May 20 '18 at 08:47

1 Answers1

15

Use $nin (not in operator):

M.findOne({list: {$nin: ['A']}}

If you $nin array condition contains single element, you can optimize further by using $ne operator:

M.findOne({list: {$ne: 'A'}}
Mạnh Quyết Nguyễn
  • 17,677
  • 1
  • 23
  • 51