两者的功能区别是什么:
db.docs.find({ 'a.b': 'c' }, { 'a.$': 1 })
和
db.docs.find({ 'a.b': 'c' }, { 'a': { $elemMatch: { b: 'c' } } })
$elemMatch 是多余的吗?索引将如何变化?
最佳答案
投影使用的差异有些微妙。在您的示例用法中,这些应该是等效查询(就索引使用而言),但 $elemMatch
示例不必要地重复查询条件。 $
投影对于这个例子来说是一个更明智的选择。
文档中提到的一个本质区别是 array field limitation对于 $
投影:
Since only one array field can appear in the query document, if the array contains documents, to specify criteria on multiple fields of these documents, use the $elemMatch operator.
关于以下投影运算符差异的一些进一步说明...
positional ($
) projection operator :
将包含在查询结果中的数组字段的内容限制为包含与查询文档匹配的第一个元素。
要求匹配的数组字段包含在查询条件中
只能在查询条件中出现单个数组字段时使用
在投影中只能使用一次
$elemMatch
projection operator
将包含在查询结果中的数组字段的内容限制为仅包含第一个与 $elemMatch 条件匹配的数组元素。
不要求匹配的数组在查询条件中
可用于为嵌入文档的数组元素匹配多个条件
$elemMatch
query operator
请注意,还有一个 $elemMatch
查询运算符执行类似的匹配,但在查询中而不是在结果投影中。将它与 $
投影结合使用的情况并不少见。
借用 example from the docs您可以同时使用两者的地方:
db.students.find(
// use $elemMatch query operator to match multiple criteria in the grades array
{ grades: {
$elemMatch: {
mean: { $gt: 70 },
grade: { $gt: 90 }
}
}},
// use $ projection to get the first matching item in the "grades" array
{ "grades.$": 1 }
)
关于mongodb - $projection 与 $elemMatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21519185/