Suppose I have a collection i.e. A.
I want to get all the keys to this collection that have particular value i.e. "hello"
{
"a": "its me hello",
"b": "it does not have value",
"c": "It has hello"
}
In that case, I want to query to return a and c keys. Which contains the string "hello".
Is there any way to do that?
Or any way to do that in spring boot?
You can do this by reshaping the data in the datasource using objectToArray
db.collection.aggregate([
{
"$project": {
"data": {
"$objectToArray": "$$ROOT"
}
}
},
{
$unwind: "$data"
},
{
"$match": {
"data.v": {
$regex: "hello"
}
}
}
])
Another advanced version here It reshapes the data back
db.collection.aggregate([
{
"$project": {
"data": {
"$objectToArray": "$$ROOT"
}
}
},
{
$unwind: "$data"
},
{
"$match": {
"data.v": {
$regex: "hello"
}
}
},
{
$group: {//Grouping back and restructuring the data so that objectToArray will bring the original format easily.
"_id": "$_id",
data: {
"$addToSet": {
k: "$data.k",
v: "$data.v"
}
}
}
},
{
"$project": {
"data": {
"$arrayToObject": "$data"
}
}
}
])
Refere the documentation of arrayToObject and objectToArray, then $regex