问题
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