MongoDB获取数组的长度

2020-04-04  本文已影响0人  gdyycn

文档

{    

    "_id" : "559581876459065623", 

    "articleId" : "559581876487065600",

    "likedUsers" : [

        {

            "userId" : "553535472413052928", 

            "time" : ISODate("2020-03-31T15:17:07.312+0000") 

      }, 

        {

            "userId" : "5496342767197265001", 

            "time" : ISODate("2020-03-31T16:20:02.633+0000")

        }   

    ]}

需求

获取articleId为“559581876487065600”的文档中likedUsers数组的长度

实现

用Mongodb查询语言实现

"match"指定匹配条件,“project”指定要返回的字段(对于JSON来说是Key);“$size”用于求likedUser数组的大小(长度),对应字段是count(可以把它看做是SQL查询语句中AS后面的别名)

db.articleLikes.aggregate(

[

  {

      $match:{

        articleId: "559581876487065600"

      }

  }, 

{ 

      $project:{ 

          count: {

              $size: "$likedUsers"

          }

      }

  }

])

用MongoTemplate实现(Spring/SpringBoot)

public Integer getLikedCount(String articleId) {

    // 查询条件

    AggregationOperation where = Aggregation.match(Criteria.where("articleId").is(articleId));

    // likedUsers为数组字段名称,count为结果字段的别名

    AggregationOperation project = Aggregation.project().andExpression("{$size: '$likedUsers'}").as("count");

    // 聚合操作

    List<AggregationOperation> operations = new ArrayList<>();

    operations.add(where);

    operations.add(project);

    Aggregation aggregation = Aggregation.newAggregation(operations); 



    / / 执行聚合操作,"articleLike"为集合名称,Document.class为返回结果类型

    AggregationResults<Document> results = mongoTemplate.aggregate(aggregation,"articleLike", Document.class);

    // 结果

    Document doc = results.getUniqueMappedResult();

    if(doc != null){

        return (Integer) doc.get("count");

    }

    return 0;

}

上一篇下一篇

猜你喜欢

热点阅读