Poor lookup aggregation performance

前端 未结 4 1329
臣服心动
臣服心动 2020-12-03 00:05

I have two collections

Posts:

{
    \"_Id\": \"1\",
    \"_PostTypeId\": \"1\",
    \"_AcceptedAnswerId\": \"192\",
    \"_CreationDate\": \"2012-02-         


        
4条回答
  •  广开言路
    2020-12-03 00:16

    as long as you're going to group by user _AccountId, you should do the $group first by _OwnerUserId then lookup only after filtering accounts having 10 this will reduce lookups:

    db.posts.aggregate([{
        $group: {
          _id: "$_OwnerUserId",
          postsCount: {
            $sum: 1
          },
          posts: {
            $push: "$$ROOT"
          } //if you need to keep original posts data
        }
      },
      {
        $match: {
          postsCount: {
            $gte: 5,
            $lte: 15
          }
        }
      },
      {
        $lookup: {
          from: "users",
          localField: "_id",
          foreignField: "_AccountId",
          as: "X"
        }
      },
      {
        $unwind: "$X"
      },
      {
        $sort: {
          postsCount: -1
        }
      },
      {
        $project: {
          postsCount: 1,
          X: 1
        }
      }
    ])

提交回复
热议问题