$elemMatch
其中“<表达式>”可以是值,也可以是带有匹配符的表达式,“$elemMatch”匹配符支持多层嵌套。
> db.sample.employee.insert( { "id": 2, "content": [ { "name": "Tom", "phone": "456", "address": "2000 Market Street, Philadelphia" } ] } )
> db.sample.employee.insert( { "id": 3, "content": { "name": "Septem", "phone": "789", "address": { "addr1": "3000 Market Street, Philadelphia", "addr2": "4000 Market Street, Philadelphia" } } } )
> db.sample.employee.find()
{
"_id": {
"$oid": "5a73ce416a3e18f64e000010"
},
"id": 1,
"content": {
"name": "Jack",
"phone": "123",
"address": "1000 Market Street, Philadelphia"
}
}
{
"_id": {
"$oid": "5a73ce476a3e18f64e000011"
},
"id": 2,
"content": [
{
"name": "Tom",
}
]
}
{
"_id": {
"$oid": "5aaa25ee48bcff191e000002"
},
"id": 3,
"content": {
"name": "Septem",
"phone": "789",
"address": {
"addr1": "3000 Market Street, Philadelphia",
"addr2": "4000 Market Street, Philadelphia"
}
}
}
Return 3 row(s).
SequoiaDB shell 运行如下:
数组匹配:
> db.sample.employee.find( { "content": { $elemMatch: { "name": "Tom", "phone": "456" } } } )
{
"_id": {
"$oid": "5822868a2b4c38286d000008"
},
"content": [
{
"name": "Tom",
"phone": "456",
"address": "2000 Market Street, Philadelphia"
}
]
}
Return 1 row(s).
使用“$regex”匹配符以及嵌套的“$elemMatch”匹配符:
> db.sample.employee.find( { "content" : { $elemMatch : { address : { $elemMatch: { addr1 : { $regex : ".*Philadelphia$" } } } } } } )
{
"_id": {
"$oid": "5a0107641f9b983f4600000d"
},
"id": 3,
"content": {
"name": "Septem",
"phone": "789",
"address": {
"addr1": "3000 Market Street, Philadelphia",
"addr2": "4000 Market Street, Philadelphia"
}
}