$elemMatch
- > db.foo.bar.insert( { "_id": 1, "class": 1, "students": [ { "name": "ZhangSan", "age": 18 }, { "name": "LiSi", "age": 19 }, { "name": "WangErmazi", "age": 18 } ] } )
- > db.foo.bar.insert( { "_id": 2, "class": 2, "students": { "name": "LinWu", "age": 18 } } )
- > 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 } ] } ] } )
- > db.foo.bar.find()
- {
- "_id": 1,
- "class": 1,
- "students": [
- {
- "name": "ZhangSan",
- "age": 18
- },
- {
- "name": "LiSi",
- "age": 19
- },
- {
- "name": "WangErmazi",
- "age": 18
- }
- ]
- }
- {
- "_id": 2,
- "class": 2,
- "students": {
- "name": "LinWu",
- "age": 18
- }
- }
- {
- "_id": 3,
- "class": 3,
- "students": [
- {
- "name": "ZhangSan",
- "age": 18,
- {
- "math": 1
- },
- {
- "english": 0
- }
- ]
- },
- {
- "name": "LiSi",
- "age": 19,
- "course": [
- {
- "math": 1
- },
- {
- "english": 1
- }
- ]
- },
- {
- "name": "WangErmazi",
- "age": 18,
- "course": [
- {
- "math": 0
- },
- {
- "english": 0
- }
- ]
- }
- ]
- }
- Return 3 row(s).
- 指定返回“age”大于 18 的元素,使用“$gt”表达式:
- > db.foo.bar.find( { "class": 1 }, { "students": { "$elemMatch": { "age": { $gt: 18 } } } } )
- {
- "_id": 1,
- "students": [
- {
- "name": "LiSi",
- "age": 19
- }
- ]
- }
- Return 1 row(s).
- 指定返回姓“Wang”的元素,使用“$regex”表达式:
- 指定返回 3 班学生数组中选择了数学的元素,使用嵌套的“$elemMatch”表达式:
- > db.foo.bar.find( { class: 3 }, { students: { $elemMatch: { course: { $elemMatch: { math: 1 } } } } } )
- {
- "_id": 3,
- "class": 3,
- "students": [
- {
- "name": "ZhangSan",
- "age": 18,
- "course": [
- {
- "math": 1
- },
- {
- "english": 0
- }
- ]
- },
- {
- "name": "LiSi",
- "age": 19,
- "course": [
- {
- "math": 1
- },
- {
- "english": 1
- }
- ]
- }
- ]
- Return 1 row(s).