MongoDB-对象?为什么我总需要_id [英] MongoDB - objects? Why do I need _id in aggregate

查看:119
本文介绍了MongoDB-对象?为什么我总需要_id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是MongoDB教程中的一个示例(此处是邮政编码:

Here is an example from MongoDB tutorial (here it collection ZIP Code db:

db.zipcodes.aggregate( [
   { $group: { _id: "$state", totalPop: { $sum: "$pop" } } },
   { $match: { totalPop: { $gte: 10*1000*1000 } } }
] )

如果我将_id替换为单词Test之类的东西,则会收到错误消息:

if I replace _id with something else like word Test, I will get error message:

"errmsg" : "exception: the group aggregate field 'Test' must be defined as an expression inside an object",
"code" : 15951,
"ok" : 0

有人可以帮助我理解为什么我的命令中需要_id吗?我以为MongoDB自动分配ID(如果使用的话不提供).

Could anybody help me understand why I need _id in my command? I thought MongoDB assigns IDs automatically, if used does not provide it.

推荐答案

$group阶段中,_id用于指定组条件.您显然需要它.

In a $group stage, _id is used to designate the group condition. You obviously need it.

如果您熟悉SQL世界,可以将其视为GROUP BY子句.

If you're familiar with the SQL world, think of it as the GROUP BY clause.

请注意,在这种情况下,_id实际上也是生成的集合中的唯一标识符,因为根据定义$group不能为该字段生成两个具有相同值的文档.

Please note, in that context too, _id is really an unique identifier in the generated collection, as by definition $group cannot produce two documents having the same value for that field.

这篇关于MongoDB-对象?为什么我总需要_id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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