, 당신은 다음과 같은 데이터 뭔가가 :
db.users.insert({_id: 100, likes: [
'pina coladas',
'long walks on the beach',
'getting caught in the rain'
]})
db.users.insert({_id: 101, likes: [
'cheese',
'bowling',
'pina coladas'
]})
db.users.insert({_id: 102, likes: [
'pina coladas',
'long walks on the beach'
]})
db.users.insert({_id: 103, likes: [
'getting caught in the rain',
'bowling'
]})
db.users.insert({_id: 104, likes: [
'pina coladas',
'long walks on the beach',
'getting caught in the rain'
]})
을하고 당신은 그들이 서로 얼마나 많은 매칭 기능 ('좋아'이 예에서) 특정 사용자에 대한 계산하고자하는 사용자? 다음 집계 파이프 라인이 작업을 수행합니다 :
user = 100
user_likes = db.users.findOne({_id: user}).likes
return_only = 2 // number of matches to return
db.users.aggregate([
{$unwind: '$likes'},
{$match: {
$and: [
{_id: {$ne: user}},
{likes: {$in: user_likes}}
]
}},
{$group: {_id: '$_id', common: {$sum: 1}}},
{$sort: {common: -1}},
{$limit: return_only}
])
이 출력됩니다 위의 예 입력 데이터를 상위 2 경기 보여주는 다음과 같은 결과 감안할 때 : 당신 만 원하는 것으로 가정
{
"result" : [
{
"_id" : 104,
"common" : 3
},
{
"_id" : 102,
"common" : 2
}
],
"ok" : 1
}
주 매우 많은 수의 사용자가있을 수 있기 때문에 매우 많은 일치 항목이 있습니다. $ limit 단계 다음에 $ sort 단계가이를 수행합니다. 그런 경우가 아니라면 파이프 라인의 마지막 두 단계를 생략하면됩니다.
도움이 되었기를 바랍니다. 추가 질문이 있으면 알려주십시오. 브루스
어떻게 0이 아닌 배열 교차를하는지 흥미로울 것입니다. 집계 프레임 워크에서? – drmirror
one_to_one 사용자를 비교하거나 one_to_many가 필요합니까? – evilive
몇 가지 샘플 문서를 제공 할 수 있습니까? 결과로 얻을 수있는 결과는 무엇입니까? – Derick