MongoDB $in Operator

MongoDB offers various kinds of operators that can be utilized to interact with the database. The $in operator is one of them.

MongoDB provides the $in operator to find a document where the value of the field is available in the specified array. This is used where we have more than one possible value to match a single key. This is very flexible and allows us to specify the criteria of different types as well as values.

Syntax of $in

{ $in: [ { }, { } , ... , { } ] }

Example of $in Operator

Suppose, we have following 'students' collection.

{ "_id" : ObjectId("5b7ddc4f529cbc23546dc4c7"), "name" : "Jorz Rai", "age" : 10, "class" : "5A" }
{ "_id" : ObjectId("5b7ddf10529cbc23546dc4c8"), "name" : "Rana Soi", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4c9"), "name" : "Andy Joya", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4ca"), "name" : "Mary Soi", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4cb"), "name" : "Priska Somya", "age" : 12, "class" : "6A" }

The given statement returns all students whose age are in [10, 11].

db.students.find({"age" : {"$in" : [10, 11]});
mongodb In operator



MongoDB $nin Operator

MongoDB provides $nin (NOT IN) operator which behaves opposite of the $in operator.

Suppose we want to find all students whose age is not in [10, 11].

db.students.find({"age" : {"$nin" : [10, 11]});

mongodb NOT IN operator





Read more articles


General Knowledge



Learn Popular Language