$elemMatch

    其中“<表达式>”可以是值,也可以是带有匹配符的表达式,“$elemMatch”匹配符支持多层嵌套。

    1. > db.sample.employee.insert( { "id": 2, "content": [ { "name": "Tom", "phone": "456", "address": "2000 Market Street, Philadelphia" } ] } )
    2. > db.sample.employee.insert( { "id": 3, "content": { "name": "Septem", "phone": "789", "address": { "addr1": "3000 Market Street, Philadelphia", "addr2": "4000 Market Street, Philadelphia" } } } )
    3. > db.sample.employee.find()
    4. {
    5. "_id": {
    6. "$oid": "5a73ce416a3e18f64e000010"
    7. },
    8. "id": 1,
    9. "content": {
    10. "name": "Jack",
    11. "phone": "123",
    12. "address": "1000 Market Street, Philadelphia"
    13. }
    14. }
    15. {
    16. "_id": {
    17. "$oid": "5a73ce476a3e18f64e000011"
    18. },
    19. "id": 2,
    20. "content": [
    21. {
    22. "name": "Tom",
    23. }
    24. ]
    25. }
    26. {
    27. "_id": {
    28. "$oid": "5aaa25ee48bcff191e000002"
    29. },
    30. "id": 3,
    31. "content": {
    32. "name": "Septem",
    33. "phone": "789",
    34. "address": {
    35. "addr1": "3000 Market Street, Philadelphia",
    36. "addr2": "4000 Market Street, Philadelphia"
    37. }
    38. }
    39. }
    40. Return 3 row(s).

    SequoiaDB shell 运行如下:

    • 数组匹配:

      1. > db.sample.employee.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).
    • 使用“$regex”匹配符以及嵌套的“$elemMatch”匹配符:

      1. > db.sample.employee.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. }