如何在mongodb中获取包含某些(字符串)值的集合的所有键 [英] How to get all keys of collection that contains certain(String) value in mongodb

查看:67
本文介绍了如何在mongodb中获取包含某些(字符串)值的集合的所有键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个集合,即 A.

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"
   }

在这种情况下,我想查询返回 a 和 c 键.其中包含字符串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?

或者有什么办法可以在 spring boot 中做到这一点?

Or any way to do that in spring boot?

推荐答案

您可以通过使用 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"
      }
    }
  }
])

参考arrayToObjectobjectToArray的文档,然后$regex

这篇关于如何在mongodb中获取包含某些(字符串)值的集合的所有键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆