mongodb 查询语句如何使用mongotemplate实现?

数据源:

{ "_id" : 1, "item" : "ABC1", "description" : "product 1", colors: [ "blue", "black", "red" ] }
{ "_id" : 2, "item" : "ABC2", "description" : "product 2", colors: [ "purple" ] }
{ "_id" : 3, "item" : "XYZ1", "description" : "product 3", colors: [ ] }
{ "_id" : 4, "item" : "ZZZ1", "description" : "product 4 - missing colors" }
{ "_id" : 5, "item" : "ZZZ2", "description" : "product 5 - colors is string", colors: "blue,red" }

查询:

db.inventory.aggregate([
   {
      $project: {
         item: 1,
         numberOfColors: { $cond: { if: { $isArray: "$colors" }, then: { $size: "$colors" }, else: "NA"} }
      }
   }
] )

那么上面的查询如何使用Mongotemplate实现呢?

阅读 1.5k
1 个回答

image.png

private void test(){
    /**
     *    {
     *       $project: {
     *          item: 1,
     *          numberOfColors: { $cond: { if: { $isArray: "$colors" }, then: { $size: "$colors" }, else: "NA"} }
     *       }
     *    }
     */
    MongoTemplate template = MongoTemplateHolder.getTemplate("dbName");
    //使用execute()方法,会使用mongodb自己的sdk回调来执行,这里就没有用spring的mongotemplate来玩了。
    ArrayList<Document> result = template.execute("collectionName", collectionCallback -> collectionCallback.aggregate(asList(
            project(Projections.fields(
                    Projections.include("item"),
                    Projections.computed("numberOfColors", new Document("$cond", new Document("if", new Document("$isArray", "$colors"))
                            .append("then", new Document("$size", "$colors"))
                            .append("else", "NA")))
            ))
    ))).into(new ArrayList<>());

    //如果用spring的mongotemplate,可以直接调用aggregate()方法。我觉得还是用mongodb自己官网的玩的舒服
    List<Document> mappedResults = template.aggregate(Aggregation.newAggregation(
            Aggregation.project("item")
                    .andExpression("cond(isArray($colors), size($colors), 'NA')").as("numberOfColors")
    ), "collectionName", Document.class).getMappedResults();

}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进