【问题标题】:how to sort the field in the mongo document which is inside array如何对数组内的mongo文档中的字段进行排序
【发布时间】:2015-09-16 10:25:14
【问题描述】:

我有一个结构化的 Mongo 文档:

{
  "_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);

有人知道如何对数组内的文档字段进行排序吗?

【问题讨论】:

  • 您正在尝试对一个元素进行排序:mongoTemplate.findOne 将始终返回一个元素。排序应用于一组结果,您告诉 mongoTemplate 按imageShared.commentDataDoc 对返回的SharedMediaCollecs 进行排序,而不是对其commentDataDoc 进行排序。

标签: spring mongodb sorting


【解决方案1】:

当您无论如何都需要获取所有文档时,在您收到来自 MongoDB 的数据后,在 C# 中进行排序可能会容易得多。一种自动执行此操作的优雅方法是用SortedSet 表示C# 对象中的commentdatadoc 数组。

但是,当您确实需要数据库端解决方案时,您可以使用aggregation pipeline 来实现,其中包含一个 $match-step、一个 $unwind 步骤和一个 $sort 步骤。要使用 C# 驱动程序执行聚合,请调用 collection.Aggregate,然后将聚合阶段设置为 the returned IAggregateFluent interface

【讨论】:

  • 感谢我确实使用了聚合。仅供参考,我正在使用 Spring MVC 在 Java 中进行操作。
  • @SriniReddyM :您能在这里提供您的解决方案吗?我有同样的要求,但还不能让它工作。
猜你喜欢
  • 2016-08-20
  • 1970-01-01
  • 2015-09-11
  • 1970-01-01
  • 1970-01-01
  • 2015-11-10
  • 1970-01-01
  • 1970-01-01
  • 2017-12-16
相关资源
最近更新 更多