how to sort the field in the mongo document which

2019-07-16 11:14发布

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)
      }
    ]
  }
};

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?

1条回答
看我几分像从前
2楼-- · 2019-07-16 11:19

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.

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.

查看更多
登录 后发表回答