【MongoDB】MongoTemplate 操作 Aggregation 中添加 addFields

一、场景

Mongodb 的 sql,文档 wallpaper 的 _id 关联文档 wallpaper_get_success 的 wallpaper_id 进行查询。

db.wallpaper.aggregate([
    {
        $addFields: {
            "_id": {
                "$toString": "$_id"
            }
        }
    },
    {
      "$lookup": {
        "from": "wallpaper_get_success",
        "localField": "_id",
        "foreignField": "wallpaper_id",
        "as": "success_id"
      }
    },
    {
      "$match": {
        "success_id": {
          "$ne": []
        }
      }
    },
    {
      "$sample": {
        "size": 5
      }
    }
])

在MongoDB数据库进行操作 sql是可以的,但是在Java中使用MongoTemplate就不行,在newAggregation 中进行 lookup,match,sample 操作都可以,但是进行 addFields 操作就不行。

Aggregation aggregation = newAggregation(
                Aggregation.fields(""), //这一截是有问题的
                lookup("wallpaper_get_success", "_id", "wallpaper_id", "success_id"),
                match(Criteria.where("success_id").ne(new WallpaperGetSuccess[]{})),
                sample(5)
        );

在这里插入图片描述
原因:$addFields 在spring mongo中不支持

二、解决方法

1.example

import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
Aggregation myDocAggr = newAggregation(
       match(Criteria.where("metaId.ref.uuid").is(someUUID)), 
       group("uuid").max("version").as("version"),
       lookup("simple","execId.ref.uuid","uuid","simple"),
       unwind("simple"),
       new AggregationOperation(){ 
         @Override 
         public Document toDocument(AggregationOperationContext aoc) {
            return new Document("$addFields",new Document("metaId.ref.name","$simple.name"));
         }
      }
)
List<Document> mydocumentList=mongoTemplate.aggregate(myDocAggr,"myDocument",Document.class).getMappedResults();

2.解决方法

把addFields 改成 new Document

关键点: 引入的 Document 类是,而不是 spring-boot-data-mongo 中的,改为import org.bson.Document;

import org.bson.Document;//关键的引入
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.*;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
import org.springframework.data.mongodb.core.query.Collation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Component;

Aggregation aggregation = newAggregation(
                aoc -> new Document("$addFields",new Document("_id",new Document("$toString","$_id"))),
                lookup("wallpaper_get_success", "_id", "wallpaper_id", "success_id"),
                match(Criteria.where("success_id").ne(new WallpaperGetSuccess[]{})),
                sample(5)
        );

不使用 lambda 表达式
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值