Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb find all except from one or two criteria

Tags:

Alright for one field matching I run:

db.bios.find( { "Country":"Netherlands" } ) 

How can I bring all documents but not the ones with "Country":"Netherlands"?

Also is it possible to bring all documents but without 2 countries?

like image 979
Diolor Avatar asked Aug 26 '13 08:08

Diolor


People also ask

How do I write two conditions in MongoDB?

In MongoDB, we can apply the multiple conditions using the and operator. By applying the and operation we will select all the documents that satisfy all the condition expressions. We can use this operator in methods like find(), update() , etc as per the requirement.

How do I exclude fields in MongoDB?

To exclude the _id field from the output documents of the $project stage, specify the exclusion of the _id field by setting it to 0 in the projection document.

How do I select a single field for all documents in a MongoDB collection?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

How do I use not condition in MongoDB?

MongoDB provides different types of logical query operators and $not operator is one of them. This operator is used to perform logical NOT operation on the specified operator expressions and select or retrieve only those documents that do not match the given operator expression.


1 Answers

Use $nin operator

For example:

db.bios.find( { Country: { $nin: ["Country1", "Country2"] } } ) 

And $ne for just one country:

db.bios.find( { Country: { $ne: "Country1" } } ) 
like image 85
Yevgeniy Anfilofyev Avatar answered Oct 22 '22 11:10

Yevgeniy Anfilofyev