点表示法与$ elemMatch [英] Dot notation vs. $elemMatch

查看:64
本文介绍了点表示法与$ elemMatch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个unitScores集合,其中每个文档都有一个id和像这样的文档数组:

I have a unitScores collection, where each document has an id and an array of documents like this:

"_id": ObjectId("52134edd5b1c2bb503000001"),
"scores": [
  {
      "userId": ObjectId("5212bf3869bf351223000002"),
      "unitId": ObjectId("521160695483658217000001"),
      "score": 33
  },
  {
      "unitId": ObjectId("521160695483658217000001"),
      "userId": ObjectId("5200f6e4006292d308000008"),
      "score": 17
  }
]

我有两个查找查询:

_id:new ObjectID(scoreId)
"scores.userId":new ObjectID(userId)
"scores.unitId":new ObjectID(unitId)

_id:new ObjectID(scoreId)
scores:
  $elemMatch:
    userId:new ObjectID(userId)
    unitId:new ObjectID(unitId)

我希望他们给出相同的结果,但是使用输入的userId和unitId

I would expect them to give the same result, but using the input userId and unitId of

userId: 5212bf3869bf351223000002
unitId: 521160695483658217000001

点表示法版本返回错误的数组条目(得分为:17),而$ elemMatch返回正确的条目(得分为:33).为什么会这样?

the dot notation version returns the wrong array entry (the one with score:17) and the $elemMatch returns the correct entry (the one with score:33). Why is that?

推荐答案

$elemMatch与点表示法逻辑不同. $elemMatch需要相同的嵌套元素才能具有值.使用点表示法可以使任何嵌套元素都具有一个值.因此,由于查询逻辑不同,您看到的结果也不同.

$elemMatch is not the same logic as dot notation. $elemMatch requires the same nested elements to have the values. Using dot notation allows for any nested elements to have an values. Thus, your seeing different results because the query logic is different.

这篇关于点表示法与$ elemMatch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆