首先找到一个字段的每个不同值的文档 [英] find first of documents for each distinct values for one field
本文介绍了首先找到一个字段的每个不同值的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于具有字段field1
,field2
,field3
等的文档集合,我需要查找
With a collection of documents with fields field1
, field2
, field3
and so on, I need to find
- 对于每个
field3
的不同值,需要获取具有field3
中每个不同值的第一个文档
field3
的不同值
- distinct values for
field3
- for each distinct value of
field3
, need to get the first document with each distinct value infield3
对于#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" }
]
推荐答案
您需要运行一个汇总操作,该操作按field3
对所有文档进行分组,并使用 $$ROOT
系统变量来引入第一个文档,例如以下:
You need to run an aggregate operation that groups all the documents by field3
and use the $first
accumulator with the $$ROOT
system variable to bring the first document, something like the following:
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
}
}
])
这篇关于首先找到一个字段的每个不同值的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文