Spring 如何对数组中的mongo文档中的字段进行排序
我有以下结构化的Mongo文档:Spring 如何对数组中的mongo文档中的字段进行排序,spring,mongodb,sorting,Spring,Mongodb,Sorting,我有以下结构化的Mongo文档: { "_id": value, "imageShared": { "imageid": value, "commentdatadoc": [ { "whocommented": value, "commenttext": value, "commenttimestamp": isodate(111) }, { "whocommented":
{
"_id": value,
"imageShared": {
"imageid": value,
"commentdatadoc": [
{
"whocommented": value,
"commenttext": value,
"commenttimestamp": isodate(111)
},
{
"whocommented": value,
"commenttext": value,
"commenttimestamp": isodate(444)
},
{
"whocommented": value,
"commenttext": value,
"commenttimestamp": isodate(222)
}
]
}
};
在这里,我想对字段commenttimestamp
desc进行排序。我尝试了下面的方法,但不起作用
Query getComments = new Query();
getComments.addCriteria(Criteria.where("imageShared.imageId").is(imageId)).
with(new Sort(Sort.Direction.DESC,"imageShared.commentDataDoc"));
SharedMediaCollec sharedMediaCollec = mongoTemplate.findOne(getComments, SharedMediaCollec.class);
有人知道如何对数组中的文档字段进行排序吗?当您需要获取所有文档时,在收到MongoDB的数据后,用C#进行排序可能会容易得多。自动执行此操作的一种优雅方法是在C#对象中用一个字符串表示
commentdatadoc
数组
但是,当您确实需要数据库端解决方案时,可以使用由$match步骤、$unwind步骤和$sort步骤组成的方法。要使用C#驱动程序执行聚合,请调用,然后将聚合阶段设置为。您正在尝试对一个元素进行排序:
mongoTemplate。findOne
将始终返回一个元素。排序应用于一组结果,您告诉mongoTemplate按imageShared.commentDataDoc
对返回的SharedMediaCollec
进行排序,而不是对其commentDataDoc
进行排序。感谢我使用了聚合。仅供参考,我正在用Java与Spring MVC一起使用。@SriniReddyM:您能在这里提供您的解决方案吗?我有同样的要求,但还没能实现。