Mongodb find query的投影字段未被排序使用。

huangapple go评论57阅读模式
英文:

Mongodb find query's projected fields are not being used by sort

问题

I am new to Mongodb, my version is 5.0.15. I was having doubt on the projected fields in the find query. I have the following query:

db.movies.find({}, {title: 1, rating: "$imdb.rating"}).sort({rating: 1})

The above query doesn't sort using the rating field. If I replace rating with imdb.rating then it works fine. Can someone explain why is it so?

Like even if I use fields which are not projected but in the original document, the command sorts using them as well. I know I can achieve the same using aggregate but I want to know the reason why this does not work. Any link to documentation would be appreciated.

Output -

Using db.movies.find({}, {title: 1, rating: "$imdb.rating"}).sort({"rating": 1})
Mongodb find query的投影字段未被排序使用。

Using db.movies.find({}, {title: 1, rating: "$imdb.rating"}).sort({"imdb.rating": 1})
Mongodb find query的投影字段未被排序使用。

英文:

I am new to Mongodb, my version is 5.0.15. I was having doubt on the projected fields in the find query. I have the following query

db.movies.find({}, {title:1, rating:"$imdb.rating"}).sort({rating:1})

The above query doesn't sort using the rating field. If I replace rating with imdb.rating then it works fine. Can someone explain why is it so?

Like even if I use fields which are not projected but in the original document, the command sorts using them as well. I know I can achieve the same using aggregate but I want to know the reason why this not works. Any link to documentation would be appreciated.

Output -

Using db.movies.find({}, {title:1, rating: "$imdb.rating"}).sort({"rating":1})
Mongodb find query的投影字段未被排序使用。

Using db.movies.find({}, {title:1, rating: "$imdb.rating"}).sort({"imdb.rating":1})

Mongodb find query的投影字段未被排序使用。

答案1

得分: 1

当MongoDB查询被排序并进行投影时,排序总是首先应用,然后才是投影。这意味着排序顺序是基于原始字段的,然后才是投影。因此,在原始文档中没有名为rating的字段。这就是为什么在排序中需要传递字段imdb.rating。由于原始文档中不存在rating字段,它将被视为null(请参见此处)。

英文:

The docs on sort mention that when Interaction with Projection

> When a set of results are both sorted and projected, the MongoDB query
> engine will always apply the sorting first.

When a MongoDB query is sorted and projected, the sorting is always applied first, before the projection. This means that the sort order is based on the original field, before it's projected.
So in your original document there is no field called rating. That is why you need to pass the field imdb.rating in your sort. Since rating is not existing in original document it will be considered as null in the sort (see this)

huangapple
  • 本文由 发表于 2023年4月4日 18:04:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75928084.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定