molleman
molleman

Reputation: 2946

how to select all documents from mongodb where one field does not equal a certain value

I am looking to select all documents thats field 'author' does not equal a certain username from my mongodb table called Posts.

so far i tried

Posts.find( { author: { $not: 'username' } } );

that didn't work, it returned everything

any ideas?

Upvotes: 0

Views: 272

Answers (1)

BatScream
BatScream

Reputation: 19700

Use the $ne operator, if the input is a string.

Posts.find( { author: { $ne: 'username' } } );

The $not operator takes an expression or a regex as input and performs a logical not on the output in case of expressions.

$not performs a logical NOT operation on the specified <operator-expression> and selects the documents that do not match the <operator-expression>. This includes documents that do not contain the field.

Syntax: { field: { $not: { <operator-expression> } } }

You could pass a regex to the $not operator this way:

var reg = new RegExp('username');
Posts.find( { author: { $not: reg } } );

Upvotes: 4

Related Questions