관련 컬렉션의 속성으로 필터링 된 관련 컬렉션 수를 기준으로 컬렉션 (예 : 상위 20 개)을 정렬하는 방법은 무엇입니까?

Murilo

다음 스키마가 있습니다.

var postSchema = new Schema({
    autor:              {type: Schema.Types.ObjectId, ref: 'user', required: true},
    texto:              {type: String},
    likes:              [{type: Schema.Types.ObjectId, ref: 'like'}],

});

var likeSchema = new Schema({
    user:       {type: Schema.Types.ObjectId, ref: 'user', required: true},
    post:       {type: Schema.Types.ObjectId, ref: 'post', required: true},
    _created_at:{type: Date},
});

컬렉션 'post'의 모든 문서를 attr '_created_at'를 사용하여 지난 24 시간 동안 (다른 기간 일 수 있음) 생성 된 관계 '좋아요'수를 기준으로 정렬하고 싶습니다.

FI "지난 24 시간 동안 좋아요를 가장 많이받은 게시물"

Aggregate를 사용하는 것이 좋은 생각이라고 들었지만 경험이 부족하고 어떤 파이프 라인을 사용해야할지 정확히 알지 못합니다.

오스카 에두아르도

게시물 ID가 충분하면 다음을 사용할 수 있습니다.

db.like.aggregate([
    //filter the likes creation dates as you need
    { $match  : { _created_at: { $gte: ISODate("2000-01-01T00:00:00.000Z"), $lt: ISODate("2020-12-31T00:00:00.000Z") } } },
    //group by post ID and count them
    { $group  : { _id: "$post", count: {$sum: 1} } },
    //sort by count, descending
    { $sort   : { count : -1 } },
    //limit the results in 20 maximum (if you need only the top 20)
    { $limit  : 20 }
])

다음과 같은 목록이 반환됩니다.

[{
    "_id" : ObjectId("5774826af4a48761f2ff0da1"),
    "count" : 5
}, ...]

그러나 동일한 쿼리에서 전체 게시물을 가져와야하는 경우 MongoDB v.3.2가 필요합니다 (이전에는 $ lookup을 사용할 수 없음). 그리고 쿼리는 다음과 같습니다.

db.like.aggregate([
    //filter the likes creation dates as you need
    { $match  : { _created_at: { $gte: ISODate("2000-01-01T00:00:00.000Z"), $lt: ISODate("2020-12-31T00:00:00.000Z") } } },
    //group by post ID and count them
    { $group  : { _id: "$post", count: {$sum: 1} } },
    //sort by count, descending
    { $sort   : { count : -1 } },
    //limit the results in 20 maximum (if you need only the top 20)
    { $limit  : 20 },
    //bring the complete post from the related collection
    { $lookup : { from: "post", localField: "_id", foreignField: "_id", as: "post" } },
    //deconstructs the array created by lookup to a single object
    { $unwind : "$post" },
    //remove the ID and include on the complete post and count (this step is optional)
    { $project: { _id: 0, post: true, count: true } }
])

그러면 다음과 같은 목록이 반환됩니다.

[{
    "count" : 5,
    "post" : {
        "_id" : ObjectId("5774826af4a48761f2ff0da1"),
        "autor" : ObjectId("577480bcf4a48761f2ff0d92"),
        "texto" : "texto06",
        "likes" : [
            ObjectId("5774882df4a48761f2ff0db9"),
            ObjectId("5774882df4a48761f2ff0dba"),
            ObjectId("5774882df4a48761f2ff0dbb"),
            ObjectId("5774882df4a48761f2ff0dbc"),
            ObjectId("5774882df4a48761f2ff0dbd")
        ]
    }
}, ...]

참조 :

https://docs.mongodb.com/manual/reference/method/db.collection.aggregate/

https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

https://docs.mongodb.com/manual/reference/method/db.collection.count/

도움이 되었기를 바랍니다!

건배!

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관