The JSON array operators provide methods to manipulate
data within an array.
Table 1.
| Operator |
Description |
Example |
| $elemMatch |
Matches array elements in a query. |
Assume a collection called contacts that
contains the following documents:
- Document 1
{"name":"Joe",
"friends":[
{"name":"Henry","age":38},
{ "name":"Mary","age":40}
]
}
- Document 2
{"name":"John",
"friends":[
{"name":"Del","age":38},
{ "name":"Chris","age":50}
]
}
- To find all documents with a friend with the name Henry and
the age is 38, run the following query:
db.contacts.find({friends:{$elemMatch:{name:"Henry", age:38}}})
- Result:
{"name":"Joe",
"friends":[
{"name":"Henry","age":38},
{ "name":"Mary","age":40}
]
}
|
| $elemMatch |
Projects array elements in the result of a query. |
- Query:
Projection: Project elements of friends array that have age as 38.
db.contacts.find({}, {"_id":0, "friends":{"$elemMatch":{"age":38}}})
- Result:
{"friends":[{"name":"Henry","age":38}]}
{"friends":[{"name":"Del","age":38}]}
|