$elemMatch

    1. > db.foo.bar.insert( { "id": 1, "content": { "name": "Jack", "phone": "123", "address": "1000 Market Street, Philadelphia" } } )
    2. > db.foo.bar.insert( { "id": 2, "content": [ { "name": "Tom", "phone": "456", "address": "2000 Market Street, Philadelphia" } ] } )
    3. > db.foo.bar.insert( { "id": 3, "content": { "name": "Septem", "phone": "789", "address": { "addr1": "3000 Market Street, Philadelphia", "addr2": "4000 Market Street, Philadelphia" } } } )
    4. > db.foo.bar.find()
    5. {
    6. "_id": {
    7. "$oid": "5a73ce416a3e18f64e000010"
    8. },
    9. "id": 1,
    10. "content": {
    11. "name": "Jack",
    12. "phone": "123",
    13. "address": "1000 Market Street, Philadelphia"
    14. }
    15. }
    16. {
    17. "_id": {
    18. "$oid": "5a73ce476a3e18f64e000011"
    19. },
    20. "id": 2,
    21. "content": [
    22. {
    23. "name": "Tom",
    24. "address": "2000 Market Street, Philadelphia"
    25. }
    26. ]
    27. }
    28. {
    29. "_id": {
    30. "$oid": "5aaa25ee48bcff191e000002"
    31. },
    32. "id": 3,
    33. "content": {
    34. "name": "Septem",
    35. "phone": "789",
    36. "address": {
    37. "addr1": "3000 Market Street, Philadelphia",
    38. "addr2": "4000 Market Street, Philadelphia"
    39. }
    40. }
    41. }
    42. Return 3 row(s).
    • 嵌套对象匹配:
    • 数组匹配:
    1. > db.foo.bar.find( { "content": { $elemMatch: { "name": "Tom", "phone": "456" } } } )
    2. {
    3. "_id": {
    4. "$oid": "5822868a2b4c38286d000008"
    5. },
    6. "content": [
    7. {
    8. "name": "Tom",
    9. "phone": "456",
    10. "address": "2000 Market Street, Philadelphia"
    11. }
    12. ]
    13. }
    14. Return 1 row(s).
    • 匹配“content”字段中子字段“phone”符合表达式“ $lte:"123" ”的记录:
    • 使用“$regex”匹配符以及嵌套的“$elemMatch”匹配符:
    1. > db.foo.bar.find( { "content" : { $elemMatch : { address : { $elemMatch: { addr1 : { $regex : ".*Philadelphia$" } } } } } } )
    2. {
    3. "_id": {
    4. "$oid": "5a0107641f9b983f4600000d"
    5. },
    6. "id": 3,
    7. "content": {
    8. "name": "Septem",
    9. "phone": "789",
    10. "address": {
    11. "addr1": "3000 Market Street, Philadelphia",
    12. "addr2": "4000 Market Street, Philadelphia"
    13. }
    14. }
    15. }