如果文档集合包含字段field1
,field2
,field3
等,我需要找到
field3
field3
的每个不同值,需要获取field3
中每个不同值的第一个文档对于#1,我可以db.myCollection.distinct("field3")
我如何进行#2?
样品采集:
[
{ "field1": 11, "field2": "toyota", "field3": "camry" },
{ "field1": 22, "field2": "toyota", "field3": "corolla" },
{ "field1": 33, "field2": "toyota", "field3": "camry" },
{ "field1": 44, "field2": "honda", "field3": "accord" },
{ "field1": 55, "field2": "honda", "field3": "accord" },
{ "field1": 66, "field2": "honda", "field3": "city" }
]
期望的结果:
[
{ "field1": 11, "field2": "toyota", "field3": "camry" },
{ "field1": 22, "field2": "toyota", "field3": "corolla" },
{ "field1": 44, "field2": "honda", "field3": "accord" },
{ "field1": 66, "field2": "honda", "field3": "city" }
]
答案 0 :(得分:4)
您需要运行一个聚合操作,按field3
对所有文档进行分组,并使用 $first
累加器与 $$ROOT
系统变量带来的第一个文件,如下所示:
db.myCollection.aggregate([
{
"$group": {
"_id": "$field3",
"doc": { "$first": "$$ROOT" }
}
}
])
或确切输出:
db.myCollection.aggregate([
{
"$group": {
"_id": "$field3",
"field1": { "$first": "$field1" },
"field2": { "$first": "$field2" }
}
},
{
"$project": {
"_id": 0,
"field3": "$_id",
"field2": 1,
"field1": 1
}
}
])
答案 1 :(得分:1)
聚合使用$ group aggregation operator
根据字段的不同值对记录进行分组根据上述说明,请尝试在MongoDB shell中执行以下查询
db.myCollection.aggregate(
// Pipeline
[
// Stage 1
{
$group: {
_id:{field3:'$field3'},
data:{$first:'$$ROOT'}
}
}
]
);
在上面提到的查询中,每个组的第一个文档的数据是通过使用$first聚合运算符获取的,而 $$ ROOT 是指当前正在通过聚合操作处理的文档