我有一個 mongoDB 資料庫,trips使用以下結構呼叫:
{'Name': 'Joe Doe',
'WentTo' :
[{ 'Destination':
{ 'City': 'Tirana',
'Country': 'Albania'}},
{ 'Destination':
{ 'City': 'Bari',
'Country': 'Italy'}},
{ 'Destination':
{ 'City': 'Pisa',
'Country': 'Italy'}} }] }
{'Name': 'Jane Doe',
'WentTo' :
[{ 'Destination':
{ 'City': 'Perth',
'Country': 'Australia'}},
{ 'Destination':
{ 'City': 'Bern',
'Country': 'Switzerland'}},
{ 'Destination':
{ 'City': 'Rome',
'Country': 'Italy'}} }] }
我想列出去過意大利的旅行者和他們去過那里的次數,如下所示:
{ "Name" : "Joe Doe", "Times in Italy" : 2 }
{ "Name" : "Jane Doe", "Times in Italy" : 1 }
我想出了這種方法,但 MongoDB 沒有輸出任何東西。
db.trips.aggregate([ {$unwind:'$WentTo.Destination'},
{$match: {'Country':'Italy'}}, {$group:{_id:'$Name', Times in Italy:{$sum:1}}}])
有任何想法嗎?
uj5u.com熱心網友回復:
也許是這樣的:
選項1:$filter/$size(在沒有同名重復記錄時更快更有效)
db.collection.aggregate([
{
"$addFields": {
"WentTo": {
$size: {
"$filter": {
"input": "$WentTo",
"as": "w",
"cond": {
"$eq": [
"$$w.Destination.Country",
"Italy"
]
}
}
}
}
}
},
{
$project: {
"Times in Italy": "$WentTo",
Name:1
}
}
])
解釋:
- 將 addFields 與 $filter 一起使用以僅匹配以意大利為 Country 的陣列元素,并使用 $size 對它們進行計數
- 根據要求將“WentTo”陣列投影為“意大利時間”和名稱。
游樂場 1
選項 2:這是您的查詢,進行了小的更正,這也涵蓋了每個名稱存在重復記錄的情況,請注意,對于更大的集合 $unwind 操作可能會影響性能并且速度很慢......
db.collection.aggregate([
{
$unwind: "$WentTo"
},
{
$match: {
"WentTo.Destination.Country": "Italy"
}
},
{
$group: {
_id: "$Name",
"Times in Italy": {
$sum: 1
}
}
}
])
游樂場 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/486082.html
