这两个MongoDB查询之间有什么区别? [英] What is the difference between these two MongoDB queries?

查看:104
本文介绍了这两个MongoDB查询之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

找出以下MongoDB查询中可能存在的差异,并理解为什么其中一个有效而另一个无效.

Find out possible differences in the following MongoDB queries and understand why one of them works and the other doesn't.

前一段时间,我发布了一个问题,寻求有关MongoDB查询的帮助:

A while ago I posted a questions asking for help regarding a MongoDB query:

在该问题中,我的查询无效,我正在寻找一种解决方法.我在评论中提供了大量帮助,最终找到了解决方案,但是似乎没人能解释为什么我的第一个错误查询不起作用,而第二个错误查询却起作用.

In that question my query didn't work, and I was looking for a way to fix it. I had a ton of help in the comments, and eventually found out the solution, but no one seems to be able to explain me why my first incorrect query doesn't work, and the second one does.

第一个(不正确的)查询:

1st (incorrect) query:

pipeline = [
        {"$group": {"_id": "$user.screen_name", "tweet_texts": {"$push": "$text"}, "count": {"$sum": 1}}},
        {"$project": {"_id": "$user.screen_name", "count": 1, "tweet_texts": 1}},
        {"$sort" : {"count" : -1}},
        {"$limit": 5}
    ]

第二次查询:

pipeline = [ 
        {"$group": {"_id": "$user.screen_name", "tweet_texts": {"$push": "$text"}, "count": {"$sum": 1}}}, 
        {"$sort" : {"count" : -1}}, 
        {"$limit": 5}
    ]

现在,专心的眼睛将看到两个查询之间的区别是项目阶段{"$project": {"_id": "$user.screen_name", "count": 1, "tweet_texts": 1}}.

Now, the mindful eye will see that the difference between the two queries is the project stage {"$project": {"_id": "$user.screen_name", "count": 1, "tweet_texts": 1}}.

当时我认为此阶段是必需的,但是由于我已经选择了$group阶段中需要的字段,因此我实际上并不需要它.实际上,这个额外且不必要的阶段正在导致测试失败.

At the time I thought this stage was necessary, but since I am already selecting the fields I need in the $group stage, I don't really need it. In fact, this additional and unnecessary stage was causing the tests to fail.

如果第一个示例中的$project阶段无用,并且与$group阶段具有相同的作用,为什么我的代码失败?

If the $project stage in the first example is useless and does the same thing as the $group stage, why was my code failing? Shouldn't it make no difference at all (since the change is idempotent?)

推荐答案

在第一个查询中,在组阶段之后,用户屏幕名称值保存在 _id 键下.因此,不在user.screen_name键下,该值将不是

In the first query, after the group stage, the user screen name value is saved under the _id key. Not under the user.screen_name key, therefore, that value will not be projected since there is no key.

如果您修改投影,请使用

If you modify your projection, using

{"$project": {"_id": "$_id", "count": 1, "tweet_texts": 1}},

{"$project": {"_id": 1, "count": 1, "tweet_texts": 1}},

{"$project": {"count": 1, "tweet_texts": 1}},

第一个管道将类似于第二个管道.

first pipeline will be similar like second pipeline.

这篇关于这两个MongoDB查询之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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