mongodb - How to get all keys of collection that contains certain(String) value in mongodb
问题描述
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
推荐阅读
- r - ifelse 语句从同一 df 行返回值
- python-3.x - 是否可以为无监督学习自定义 tf.estimator,自定义评估图没有损失?
- r - 在 R 中构建迭代 URL 时转义“%”
- c++ - std::map 给出类型转换错误,但仅在为 x86 编译时
- python - 使用 Pandas,我可以检测到固定列中的错误元素并返回该值吗?
- c++ - 在循环中创建指针并释放内存的最佳做法是什么
- sql - SQL选择多个连接和MAX(字段)结果
- php - 使用 Laravel Scheduler 时视图未导出到文件
- python - 在 python3 中安装 Gensim
- css - CSS边框角半径