【问题标题】:How to get property value direct from mongodb in JAVAJAVA中如何直接从mongodb获取属性值
【发布时间】:2023-02-07 11:25:19
【问题描述】:

大家好,我收集了如下文件。我想直接从角色数组中获取参数的“权限”:_id、groups._id、roles._id 使用 java mongo 驱动程序。

{
  "_id": 1000002,
  "groups": [
    {
      "_id": 1,
      "roles": [
        {
          "rights": 3,
          "_id": 1
        },
        {
          "rights": 7,
          "_id": 2
        },
        {
          "rights": 3,
          "_id": 3
        }
      ]
    }
  ],
  "timestamp": {
    "$date": {
      "$numberLong": "1675267318028"
    }
  },
  "users": [
    {
      "accessProviderId": 1,
      "rights": 1,
      "_id": 4
    },
    {
      "accessProviderId": 1,
      "rights": 3,
      "_id": 5
    }
  ]
}

我有代表该文档的 AccessListItem 类,我使用 Bson 过滤器从 mongo 获取它,但是在获取之后我必须通过 java 函数获取信息。我想直接从 mongo base 获取 int 值。

        Bson fileFilter = Filters.eq("_id", itemId);
        Bson groupFilter = Filters.elemMatch("groups", Document.parse("{_id:"+groupId+"}"));
        Bson roleFilter = Filters.elemMatch("groups.roles", Document.parse("{_id:"+role+"}"));

        Bson finalFilter = Filters.and(fileFilter, Filters.and(groupFilter,roleFilter));

        MongoCollection<AccessListItem> accessListItemMongoCollection =      MongoUtils.getAccessCollection(type);
        AccessListItem accessListItem =  accessListItemMongoCollection.find(finalFilter).first();

【问题讨论】:

    标签: java mongodb mongoose spring-data-mongodb mongodb-java


    【解决方案1】:

    简短的回答是你不能。

    MongoDB 设计用于返回文档,即包含键值对的对象。 MongoDB 查询没有只返回一个值的机制,即它永远不会只返回3[3]

    您可以在末尾使用带有 $project 阶段的聚合来为您提供一个简化的对象,例如:

    { rights: 3}
    

    在 javascript 中可能看起来像:

    db.collection.aggregate([
      {$match: {
          _id: itemId,
          "groups._id": groupId,
          "groups.roles._id": role
      }},
      {$project: {
          _id: 0,
          group: {
            $first: {
              $filter: {
                input: "$groups",
                cond: {$eq: ["$$this._id",groupId]}
              }
            }
          }
      }},
      {$project: {
          "roles": {
            $first: {
              $filter: {
                input: "$group.roles",
                cond: { $eq: [ "$$this._id",role]}
              }
            }
          }
      }},
      {$project: {
          rights: "$roles.rights"
      }}
    ])
    

    示例:Playground

    我不熟悉 spring boot,所以我不确定在 Java 中会是什么样子。

    【讨论】:

      猜你喜欢
      • 2015-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多