英文:
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})
Using db.movies.find({}, {title: 1, rating: "$imdb.rating"}).sort({"imdb.rating": 1})
英文:
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})
Using db.movies.find({}, {title:1, rating: "$imdb.rating"}).sort({"imdb.rating":1})
答案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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论