I am trying to fetch an element from an array in the MongoDB in my Spring Framework project.
I have find the solution for MongoDB shell, but I do not know how to implement it by Spring.data.core.aggregation, one of aggregation operator @addFields is not supported by Spring.
Could anyone tell me how to replace this @addField or how to implement in it another way? Thank you so much!!!
MongoDB sample data:
{
"_id" : 15,
"items" : [
{
"columns" : [
{
"title" : "hhh",
"value" : 10
},
{
"title" : "hahaha",
"value" : 20
}
]
},
{
"columns" : [
{
"title" : "hiii",
"value" : 50
}
]
}
]
}
Expected result:
{
"_id" : 15,
"items" : [
{
"columns" : [
{
"title" : "hahaha",
"value" : 20
}
]
},
{
"columns" : []
}
]
}
The solution for MongoDB Shell:
let value = "hahaha";
db.coll.aggregate([
{
"$addFields": {
"items": {
"$map": {
"input": "$items",
"as": "item",
"in": {
"columns": {
"$filter": {
"input": "$$item.columns",
"as": "elt",
"cond": { "$eq": [ "$$elt.title", value ] }
}
}
}
}
}
}
}
])
MongoDB version: 3.4.1
Spring version: 1.4.3