这是我第一次在Java中使用Mongo,我在使用聚合查询时遇到了一些问题。我可以在扩展MongoRepository<T, ID>
的存储库接口中使用@Query
注释来执行一些简单的查询。当您在Spring-Data中进行长时间的聚合时,知道采取哪种方法将会很有帮助。
db.post.aggregate([
{
$match: {}
},
{
$lookup: {
from: "users",
localField: "postedBy",
foreignField: "_id",
as: "user"
}
},
{
$group: {
_id: {
username: "$user.name",
title: "$title",
description: "$description",
upvotes: { $size: "$upvotesBy" },
upvotesBy: "$upvotesBy",
isUpvoted: { $in: [req.query.userId, "$upvotesBy"] },
isPinned: {
$cond: {
if: { $gte: [{ $size: "$upvotesBy" }, 3] },
then: true,
else: false
}
},
file: "$file",
createdAt: {
$dateToString: {
format: "%H:%M %d-%m-%Y",
timezone: "+01",
date: "$createdAt"
}
},
id: "$_id"
}
}
},
{ $sort: { "_id.isPinned": -1, "_id.createdAt": -1 } }
])
mongoTemplate
或者原生的 MongoDB 驱动程序。可以参考这篇文章。 - Valijon