Search This Blog

2023/04/16

Mongodb:$elemMatch

Here we look into $elemMatch in mongoDb.

we will use collection "shapes".

//drop collection if pre exists
db.shapes.drop()

add some document with sample data to collection "shapes".

db.shapes.insertMany([
{
"shapes": [
{
"shape": "square",
"color": "blue"
},
{
"shape": "circle",
"color": "red"
}
]
},
{
"shapes": [
{
"shape": "square",
"color": "black"
},
{
"shape": "circle",
"color": "green"
}
]
}
])

Now lets run following query

db.shapes.find(
{"shapes.color": "red"},{}
);

Output:
[
{
_id: ObjectId('662677bc30f542d208ef6352'),
shapes: [
{ shape: 'square', color: 'blue' },
{ shape: 'circle', color: 'red' }
]
}
]

same query can be written as

db.shapes.find(
{
shapes: {$elemMatch: {color: "red"}}
}
);

This will give same result as previous one.

Tbis query gives us all documents where "shapes.color" is red.
Here our first documents matches the condition.

Yet in our output "shapes" array contain shape "square" which
is not "red".We can filter out inner array too.

Here is how we can do it.

db.shapes.find(
{"shapes.color": "red"},
{
_id: 1,
shapes: {$elemMatch: {color: "red"}}
}
);

Output:
[
{
_id: ObjectId('662677bc30f542d208ef6352'),
shapes: [ { shape: 'circle', color: 'red' } ]
}
]

Now our result has only shapes which are "red".



No comments:

Post a Comment