1
저는 MongoDB를 처음 접했고 현재 상황에 직면하고 있습니다. 아래는 내가 가지고있는 모든 데이터베이스에서이 개 샘플 기록은 다음과 같습니다MongoDB 집계 결과를 중첩 배열로
{
"Country": "US",
"Years": [
{
"Year": "2016",
"Links": [ "https://wikileaks.org/gifiles/docs/11/111533_-latam-centam-brief-110822-.html",
"https://wikileaks.org/plusd/cables/1979PANAMA06344_e.html",
"https://wikileaks.org/gifiles/docs/90/9058_wax-12312008-csv-.html" ]
},
{
"Year": "2013",
"Links": [ ""https://wikileaks.org/gifiles/docs/11/111533_-latam-centam-brief-110822-.html",
"https://wikileaks.org/plusd/cables/1979PANAMA06344_e.html",
"https://wikileaks.org/gifiles/docs/90/9058_wax-12312008-csv-.html" ]
}
]
"Link_Count": 6
}
{
"Country": "UK",
"Years": [
{
"Year": "2009",
"Links": [ "https://wikileaks.org/gifiles/docs/11/111533_-latam-centam-brief-110822-.html",
"https://wikileaks.org/plusd/cables/1979PANAMA06344_e.html",
"https://wikileaks.org/gifiles/docs/90/9058_wax-12312008-csv-.html" ]
},
{
"Year": "2011",
"Links": [ ""https://wikileaks.org/gifiles/docs/11/111533_-latam-centam-brief-110822-.html",
"https://wikileaks.org/plusd/cables/1979PANAMA06344_e.html"]
}
]
"Link_Count": 5
}
내가 그것을 집계하려고했지만, I : 기본적으로
{
"_id": 1,
"Record": 1,
"Link": [ "https://wikileaks.org/plusd/cables/1979PANAMA06344_e.html" ],
"Location": [ "USA", "PAN", "USA", "USA", "PAN" ],
"Organization": [ "GN", "SOUTHCOM", "UCMJ", "PRC" ],
"Date": [ "2016" ],
"People": [ "P.Walter" ]
}
{
"_id": 2,
"Record": 2,
"Link": [ "https://wikileaks.org/gifiles/docs/11/111533_-latam-centam-brief-110822-.html" ],
"Location": [ "NIC", "GTM", "JAM", "GTM", "PAN" ],
"Organization": [ "CENTAM", "Calibre Mining Corporation", "STRATFOR", "Alder Resources" ],
"Date": [ "2013" ],
"People": [ "Daniel Ortega", "Hugo Chavez", "Paulo Gregoire" ]
}
는,이 같은 결과를 얻으려고 출력물에 주어진 것처럼 내가 원하는 것을 얻을 수 없습니다. $ 위치 내에서 발견 중복이 있기 때문에 $ 위치에
db.test.aggregate([
{
"$unwind": "$Location"
},
{
"$group" : {
"_id": {
"Country": "$Location",
"Year": "$Date",
"Links": "$Link"
},
Loc: {
$addToSet: "$Location"
}
}
},
{
"$unwind": "$Loc"
},
{
"$group": {
"_id": "$Loc",
"Years": { "$push": {
"Year": "$_id.Year",
"Links": "$_id.Links"
}
}
}
}
]).toArray()
내가 $ 긴장을 풀고 사용 $ addToSet : 여기 내 쿼리입니다. 어떤 제안이나 해결책이든 열려 있으므로 알려주세요! 미리 감사드립니다!
db.test.aggregate([{
"$unwind": "$Location"
}, {
"$unwind": "$Date"
}, {
"$unwind": "$Link"
}, {
"$group": {
"_id": {
"Country": "$Location",
"Year": "$Date"
},
Links: {
$addToSet: "$Link"
}
}
}, {
"$group": {
"_id": "$_id.Country",
Years: {
$push: {
"Year": "$_id.Year",
"Links": "$Links"
}
},
Link_Count: { $sum: { $size: "$Links" } }
}
}])
아이디어는 새로운 배열에 $push
링크 할 수 있도록 모든 배열 $unwind
에, 그리고 마지막 $group
스테이지 $size
로 그룹화 기록을 계산 :
안녕하세요, 귀하의 의견에 감사드립니다. 위의 쿼리를 사용하여 원하는 출력을 얻을 수있었습니다. 그러나, 링크에 $ addToSet을 사용하는 것이 가능한지 궁금한 점이 있습니다. 고유 한 링크 만 얻으려는 것입니다. 위의 쿼리는 나에게 중복을주었습니다. 나는 정말로 너를 괴롭히는 것에 대해 너의 도움과 미안을 진심으로 감사한다! – Levi0000
'Years.Links' 배열에서 고유 한 값을 얻고 국가의 고유 한'Links' 값의 개수를'Link_Count'로 갖도록 업데이트 된 답변을보십시오 –