$and operator: MongoDB

Lets quickly learn about using $and operator in MongoDB.

Related Read:
$exists, $type, $regex operators: MongoDB
$or (Union) Operator: MongoDB

Documents in our collection
test database, names collection.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "name" : "Alia" }
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }
{ "_id" : ObjectId("53be5d5904cc1cb0a7bfc3c2"), "name" : "Chameli" }
{ "_id" : ObjectId("53be5d6104cc1cb0a7bfc3c3"), "name" : "Dev D" }
{ "_id" : ObjectId("53be5d6804cc1cb0a7bfc3c4"), "name" : "Emli" }
{ "_id" : ObjectId("53be5d8604cc1cb0a7bfc3c5"), "name" : "Farhan" }
{ "_id" : ObjectId("53be5d9204cc1cb0a7bfc3c6"), "name" : "Gangs" }
{ "_id" : ObjectId("53be5d9904cc1cb0a7bfc3c7"), "name" : "Hum" }
{ "_id" : ObjectId("53be5e3704cc1cb0a7bfc3c8"), "name" : 25 }
{
        "_id" : ObjectId("53beaa0f6a8a31dc255d4589"),
        "name" : "Satish",
        "age" : 27
}

$and operator: MongoDB


[youtube https://www.youtube.com/watch?v=Ur0Mmj7yEOI]

YouTube Link: https://www.youtube.com/watch?v=Ur0Mmj7yEOI [Watch the Video In Full Screen.]



1
2
3
> db.names.find({$and: [{"name": {$regex: "e"}}, {"name": {$gt: "C"}}]});
{ "_id" : ObjectId("53be5d5904cc1cb0a7bfc3c2"), "name" : "Chameli" }
{ "_id" : ObjectId("53be5d6104cc1cb0a7bfc3c3"), "name" : "Dev D" }

As you can see, $and works/outputs results only when all the conditions in the array is met. i.e., in above command, the name must have small letter ā€œeā€ in it and must be lexicographically greater than capital letter ā€œCā€.