Reputation: 101
I have a mongodb query which works fine
db.user.aggregate([
{
"$project": {
"data": {
"$objectToArray": "$$ROOT"
}
}
},
{
$unwind: "$data"
},
{
"$match": {
"data.v": {
$regex: "Mohit Chandani"
}
}
}
])
It basically, get all the document having the value Mohit Chandani and here is the output:
{ "_id" : "b387d728-1feb-45b6-bdec-dafdf22685e2", "data" : { "k" : "fullName", "v" : "Mohit Chandani" } }
{ "_id" : "8e35c497-4296-4ad9-8af6-9187dc0344f7", "data" : { "k" : "fullName", "v" : "Mohit Chandani" } }
{ "_id" : "c38b6767-6665-46b8-bd29-645c41d03850", "data" : { "k" : "fullName", "v" : "Mohit Chandani" } }
I need this query to be converted for my spring boot application and I am writing the following:-
Aggregation aggregation = Aggregation.newAggregation(Aggregation.project(Aggregation.ROOT), Aggregation.match(Criteria.where(connectionRequest.getWord())));
It would be helpful to know which approach to take when you do long aggregations in Spring-Data.
Upvotes: 0
Views: 5556
Reputation: 8894
This might help you, Hope you are using MongoTemplate
for aggregation.
@Autowired
private MongoTemplate mongoTemplate;
And the code for above script is
public List<Object> test() {
Aggregation.newAggregation(
project().and(ObjectOperators.valueOf(ROOT).toArray()).as("data"),
unwind("data"),
match(Criteria.where("data.v").regex("Mohit Chandani")
)
).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());
return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), Object.class).getMappedResults();
}
I'm not sure the project()
of above code would work, because I haven't tried it. I referred it form Spring data mongodb
If it doesn't work, this would definitely work. Few opetaiotion are not suppored in spring data like $addFields
, $filter
.. So we do a Trick to convert
public List<Object> test() {
Aggregation aggregation = Aggregation.newAggregation(
p-> new Document("$project",
new Document("data",
new Document("$objectToArray","$$ROOT")
)
),
unwind("data"),
match(Criteria.where("data.v").regex("Mohit Chandani"))
).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());
return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), Object.class).getMappedResults();
}
Upvotes: 1