MongoDB-对象?为什么我总需要_id [英] MongoDB - objects? Why do I need _id in aggregate
问题描述
这是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屋!