How to call MongoDB addFields in Spring Mongo?

萝らか妹 提交于 2021-02-11 14:41:44

问题


I have the following type of object in my MongoDB

{
    ...,
    "name": {
        "en": "...",
        "am": "...",
        "ru": "..."
    },
    ...
}

Now I want to run the following query using Spring Data Mongo

db.categories.aggregate({$addFields: {'name': '$name.am'}})

where the am part in $name.am is the locale of the name, hence it must be dynamic. I looked through the MongoTemplate API, and as far as I found, there is no support of addFields operation. Is there any way to achieve this?


回答1:


You need to implement AggregationOperation

Single use

AggregationOperation addFields = new AggregationOperation() {

    @Override
    public Document toDocument(AggregationOperationContext context) {
        return new Document("$addFields", new Document("name", "$name.am"));
    }

};

Generic

public AggregationOperation aggregateAddFields(final String field, final String valueExpresion) {

    AggregationOperation addFields = new AggregationOperation() {

        @Override
        public Document toDocument(AggregationOperationContext context) {
            return new Document("$addFields", new Document(field, valueExpresion));
        }
    };

    return addFields;
}

...

AggregationOperation addFields = aggregateAddFields("name", "$name.am");


来源:https://stackoverflow.com/questions/60892628/how-to-call-mongodb-addfields-in-spring-mongo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!