1

두 개의 모음이 있습니다. userscommunities. 내 사용자는 내가 같은 사용자 스키마의 배열로 linkedCommunities이 많은 지역 사회에 링크 할 수 있습니다 내 communities보기에배열에서 ObjectID의 발생 횟수를 어떻게 집계합니까?

const userSchema = new Schema({ 
    linkedCommunities: [ 
    { 
     type: mongoose.Schema.ObjectId, 
     ref: 'Community' 
    } 
    ] 
}); 

내가 각 커뮤니티에 연결 users의 수를 표시 할, 그래서 읽을 것 같은 : 나는 Community 모델에 발견 할 때

| Community | Number of users | 
| --------- | --------------- | 
| Community 1 | 45    | 
| Community 2 | 78    | 
| Community 4 | 107    | 

은 이상적으로는 필드 linkedUserCount 같은라고합니다.

어쨌든 aggregate을 사용하여 이것을 달성 할 수 있다고 확신하지만 올바른 파이프 라인 운영자와 주문을 찾기 위해 애 쓰고 있습니다.

db.users.aggregate([ 
    { 
    $unwind : "$linkedCommunities" 
    }, 
    { 
    $group : { 
     _id : "$linkedCommunities", 
     count: { $sum: 1 } 
    } 
    }, 
    { 
    $project: { 
     _id: 0, 
     community: "$_id", 
     count: "$count" 
    } 
    } 
]) 

가 그것에게 시험을주고 당신이 어떤 문제가 있으면 알려 주시기 :

답변

1

당신은 다음과 같은 MongoDB의 쿼리를 사용하여 필요한 결과를 얻을 수 있습니다. 여기

+0

이 나에게 수를주는 최적입니다. 감사. 이제는 모든 것을 연결하는 방법을 알아야합니다. –

2

어쩌면 유를 도울 수,

users.aggregate([ 
{ 
    $lookup: 
     { 
      from: "Community", 
      localField: "linkedCommunities", 
      foreignField: "_id", 
      as: "linkedcommunities" 
     }} 
,{ 
    $unwind: "$linkedCommunities" 
}, 
{ 
    $group : { 
     _id : "$linkedCommunities", 
     count: { $sum: 1 } 
    } 
}, 
{ 
    $project: { 
     _id: 0, 
     community: "$_id", 
     count: "$count" 
    } 
}]} 
관련 문제