如何在 Spring Mongo 中调用 MongoDB addFields? [英] How to call MongoDB addFields in Spring Mongo?
本文介绍了如何在 Spring Mongo 中调用 MongoDB addFields?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的 MongoDB 中有以下类型的对象
I have the following type of object in my MongoDB
{
...,
"name": {
"en": "...",
"am": "...",
"ru": "..."
},
...
}
现在我想使用 Spring Data Mongo 运行以下查询
Now I want to run the following query using Spring Data Mongo
db.categories.aggregate({$addFields: {'name': '$name.am'}})
其中 $name.am
中的 am
部分是名称的语言环境,因此它必须是动态的.我查看了 MongoTemplate API,据我所知,不支持 addFields
操作.有什么办法可以做到这一点吗?
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?
推荐答案
你需要实现 AggregationOperation
AggregationOperation addFields = new AggregationOperation() {
@Override
public Document toDocument(AggregationOperationContext context) {
return new Document("$addFields", new Document("name", "$name.am"));
}
};
通用
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");
这篇关于如何在 Spring Mongo 中调用 MongoDB addFields?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文