$elementmatch in mongodb
- Mohamed Sahir
- Sep 16, 2020
The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.
You cannot specify a $where expression in an $elemMatch You cannot specify a $text query expression in an $elemMatch.
Question?Now I want to display an elements in values that first element of them are "a" in array.
{
"values":
[
["a","231"],
["b","232"],
["c","233"],
["a","235"]
]
}
Query:
db.collection.find(
{},
{
'values': {
$elemMatch: {
$elemMatch: {
$in: ['a']
}
}
}
}
)
{
"_id": ObjectId("562e7c594c12942f08fe4192"),
"shapes": [
{
"shape": "square",
"color": "blue"
},
{
"shape": "circle",
"color": "red"
}
]
},
{
"_id": ObjectId("562e7c594c12942f08fe4193"),
"shapes": [
{
"shape": "square",
"color": "black"
},
{
"shape": "circle",
"color": "red"
}
]
}
Query:
db.collection.find({
shapes: {
"$elemMatch": {
color: "red"
}
}
},
{
"shapes.color": 1
})
Comments
Post a Comment