如何对数组内部的mongo文档中的字段进行排序 [英] how to sort the field in the mongo document which is inside array
问题描述
下面有一个结构化的Mongo文档:
I have below a structured Mongo Document:
{
"_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进行排序.我尝试了下面的方法,但是它不起作用...
Here I want to sort the field commenttimestamp
desc. I tried the way below but it is not working...
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);
有人知道如何对数组内部的文档字段进行排序吗?
Does anyone have an idea how to sort a document field which is inside array?
推荐答案
无论如何,您都需要获取所有文档时,从MongoDB接收数据后,使用C#进行排序可能会容易得多.自动执行此操作的一种优雅方法是使用
When you need to get all documents anyway, it might be far easier to do the sorting in C# after you received the data from MongoDB. An elegant way to do this automatically would be to represent the commentdatadoc
array in your C# object with a SortedSet.
但是,如果您确实需要数据库方面的解决方案,则可以使用聚合管道,包括一个$ match步骤,一个$ unwind步骤和一个$ sort步骤.要使用C#驱动程序执行聚合,请先调用 collection.Aggregate
将聚集阶段设置为返回的IAggregateFluent
接口.
But when you definitely want a database-sided solution, you can do it with an aggregation pipeline consisting of a $match-step, a $unwind step and a $sort step. To perform an aggregation with the C# driver, call collection.Aggregate
and then set the aggregation stages at the returned IAggregateFluent
interface.
这篇关于如何对数组内部的mongo文档中的字段进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!