0

Mongodb $elemMatch操作符

Posted by 撒得一地 on 2016年3月31日 in Mongodb教程

$elemMatch

$elemMatch 操作符输出满足这样条件的文档,即文档中field数组中至少一个元素满足全部指定的匹配条件。

{<field>:{$elemMatch:{ query1,query2, ... }}}

在 $elemMatch 表达式中,如果你仅仅指定一个查询条件,那么你不需要使用$elemMatch 操作符。

实例,假设scores数据库有以下文档:

>db.scores.find()
{ _id: 1, results: [ 82, 85, 88 ] }
{ _id: 2, results: [ 75, 88, 89 ] }
>db.scores.find(
   {results:{$elemMatch:{$gte:80,$lt:85}}}
)
{ _id: 1, results: [ 82, 85, 88 ] }

上面的查询输出满足以下条件的文档:只要results数组中至少存在一个元素大于等于80且小于85。所以在 [ 82, 85, 88 ]数组中,82刚好满足,而在[ 75, 88, 89 ]中,没有一个元素满足上述条件。

再看一个例子,假设survey数据中存在如下文档:

{ _id:1,results:[{product:"abc",score:10},{product:"xyz",score:5}]}
{ _id:2,results:[{product:"abc",score:8},{product:"xyz",score:7}]}
{ _id: 3,results:[{product:"abc",score:7}, {product:"xyz",score:8}]}

假设要查询的文档中,results数组中至少一个元素 product 等于"xyz"且 score 大于等于8,那么可以使用下面的查询语句:

db.survey.find(
   { results:{$elemMatch:{product:"xyz",score:{$gte:8}}}}
)
{ _id: 3,results:[{product:"abc",score:7},{product:"xyz",score: 8}]}

单一条件查询

看下面的例子,假设 $elemMatch 操作符只指定一个查询条件{ product: "xyz" }:

db.survey.find(
   { results:{$elemMatch:{product:"xyz"}}}
)

上面的例子中,因为 $elemMatch 操作符只指定一个查询条件,那么当只有一个查询条件时,使用 $elemMatch 操作符有点大材小用了,你可以将上面的查询替换成下面这样子:

db.survey.find(
   { "results.product": "xyz" }
)

本文地址:http://coderschool.cn/1763.html

上一篇:

下一篇:

相关推荐

发表评论

电子邮件地址不会被公开。 必填项已用*标注

7 + 5 = ?

网站地图|XML地图

Copyright © 2015-2024 技术拉近你我! All rights reserved.
闽ICP备15015576号-1 版权所有©psz.