Wetts's blog

Stay Hungry, Stay Foolish.

0%

MongoDB-elemMatch

$elemMatch 是用来匹配数组内的元素的。

. 容易产生混淆。

$elemMatch. 对比

初始化源数据

1
2
3
4
5
6
db.em.insert({"arr":[{"e1":"a","e2":11},{"e1":"b","e2":12},{"e1":"c","e2":13},{"e1":"d","e2":14}]})
db.em.insert({"arr":[{"e1":"a","e2":21},{"e1":"b","e2":22},{"e1":"c","e2":23},{"e1":"d","e2":24}]})
db.em.insert({"arr":[{"e1":"a","e2":31},{"e1":"b","e2":32},{"e1":"c","e2
":33},{"e1":"d","e2":34}]})
db.em.insert({"arr":[{"e1":"a","e2":41},{"e1":"b","e2":42},{"e1":"c","e2":43},{"e1":"d","e2":44}]})
db.em.insert({"arr":[{"e1":"a","e2":51},{"e1":"b","e2":52},{"e1":"c","e2":53},{"e1":"d","e2":54}]})

. 查询

db.em.find({"arr":{$elemMatch: {"e1":"a","e2":32}}})

无结果集

$elemMatch 查询

db.em.find({"arr.e1":"a","arr.e2":32})

查询结果如下:
1

总结

  • $elemMatch:数组内单个元素匹配则符合
  • .:数组内多个元素能分别匹配上条件即符合