MongoDB $and Operator

Logical operators are vital in any programming language and they help us take decisions dependent on specific conditions. Assume we need to combine the result of two conditions, then at that point logical AND operator help us in producing the final result.

MongoDB $and operator performs AND operation on an array of two or more expressions.

Syntax of $and Operator

"$and" : [expr1[, expr2, ..., exprN]]

It returns true if all expressions are true.

Example of $and Operator

Suppose, we have the 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 select documents where the age equals to 11 and class equals to '5C'.

db.students.find({
	$and : [
		{"age" : 11},
		{"class" : '5C'}
	]
}).pretty();

mongodb AND operator





Read more articles


General Knowledge



Learn Popular Language