$elemMatch

    1. > db.foo.bar.insert( { "_id": 1, "class": 1, "students": [ { "name": "ZhangSan", "age": 18 }, { "name": "LiSi", "age": 19 }, { "name": "WangErmazi", "age": 18 } ] } )
    2. > db.foo.bar.insert( { "_id": 2, "class": 2, "students": { "name": "LinWu", "age": 18 } } )
    3. > db.foo.bar.insert( { "_id": 3, "class": 3, "students": [ { "name": "ZhangSan", "age": 18, course: [ { math: 1 }, { english: 0 } ] }, { "name": "LiSi", "age": 19, course: [ { math: 1 }, { english: 1 } ] }, { "name": "WangErmazi", "age": 18, course: [ { math: 0 }, { english: 0 } ] } ] } )
    4. > db.foo.bar.find()
    5. {
    6. "_id": 1,
    7. "class": 1,
    8. "students": [
    9. {
    10. "name": "ZhangSan",
    11. "age": 18
    12. },
    13. {
    14. "name": "LiSi",
    15. "age": 19
    16. },
    17. {
    18. "name": "WangErmazi",
    19. "age": 18
    20. }
    21. ]
    22. }
    23. {
    24. "_id": 2,
    25. "class": 2,
    26. "students": {
    27. "name": "LinWu",
    28. "age": 18
    29. }
    30. }
    31. {
    32. "_id": 3,
    33. "class": 3,
    34. "students": [
    35. {
    36. "name": "ZhangSan",
    37. "age": 18,
    38. {
    39. "math": 1
    40. },
    41. {
    42. "english": 0
    43. }
    44. ]
    45. },
    46. {
    47. "name": "LiSi",
    48. "age": 19,
    49. "course": [
    50. {
    51. "math": 1
    52. },
    53. {
    54. "english": 1
    55. }
    56. ]
    57. },
    58. {
    59. "name": "WangErmazi",
    60. "age": 18,
    61. "course": [
    62. {
    63. "math": 0
    64. },
    65. {
    66. "english": 0
    67. }
    68. ]
    69. }
    70. ]
    71. }
    72. Return 3 row(s).
    • 指定返回“age”等于 18 的元素:
    • 指定返回“age”大于 18 的元素,使用“$gt”表达式:
    1. > db.foo.bar.find( { "class": 1 }, { "students": { "$elemMatch": { "age": { $gt: 18 } } } } )
    2. {
    3. "_id": 1,
    4. "students": [
    5. {
    6. "name": "LiSi",
    7. "age": 19
    8. }
    9. ]
    10. }
    11. Return 1 row(s).
    • 指定返回姓“Wang”的元素,使用“$regex”表达式:
    • 指定返回 3 班学生数组中选择了数学的元素,使用嵌套的“$elemMatch”表达式:
    1. > db.foo.bar.find( { class: 3 }, { students: { $elemMatch: { course: { $elemMatch: { math: 1 } } } } } )
    2. {
    3. "_id": 3,
    4. "class": 3,
    5. "students": [
    6. {
    7. "name": "ZhangSan",
    8. "age": 18,
    9. "course": [
    10. {
    11. "math": 1
    12. },
    13. {
    14. "english": 0
    15. }
    16. ]
    17. },
    18. {
    19. "name": "LiSi",
    20. "age": 19,
    21. "course": [
    22. {
    23. "math": 1
    24. },
    25. {
    26. "english": 1
    27. }
    28. ]
    29. }
    30. ]
    31. Return 1 row(s).