【问题标题】:MongoDb Spring find in nested objectMongoDb Spring 在嵌套对象中查找
【发布时间】:2016-03-05 03:22:25
【问题描述】:

我正在使用 Spring Data Mongodb 和这样的文档:

{
    "_id" : ObjectId("565c5ed433a140520cdedd7f"),
    "attributes" : {
        "565c5ed433a140520cdedd73" : "333563851"
    },
    "listId" : ObjectId("565c57aaf316d71fd4e4d0a0"),
    "international" : false,
    "countryCode" : 33,
    "deleted" : false
}

我想查询我的集合以搜索属性对象中的值(在值而不是键中)。

例如这样:

@Query("{'listId': ?0, $or: [{'attributes.*':{$regex: ?1}}], 'deleted':false}")
Page<PTContact> findByListIdAndByAttributesContaining(ObjectId listId, String val, Pageable pageable);

但我不确定能否做到这一点。有什么想法可以帮助我吗?

最好的问候

编辑:我的解决方案

嗯,我所做的很简单。我知道该 listId 的每个 id(属性字段中的键),所以我创建了一个自定义 mongo 操作

    Criteria[] fieldsCriteria = new Criteria[fields.size()];
    for (int i = 0; i < fields.size(); i++) {
        fieldsCriteria[i] = Criteria.where("attributes." + fields.get(i).getId()).regex(val, "i");
    }
    Query query = Query.query(Criteria.where("listId").is(listId).orOperator(fieldsCriteria));
    return new PageImpl<>(operations.find(query.with(pageable), PTContact.class), pageable, operations.count(query, PTContact.class));

有一些分页.. 它有效

【问题讨论】:

    标签: java regex spring mongodb spring-data


    【解决方案1】:

    我认为你必须改变attributes的结构:

    attributes : [{
            key : "565c5ed433a140520cdedd73",
            value: "333563851"
        }, {
            key : "...",
            value: "..."
        }
    ]
    

    然后像这样更改您的请求:

    {'attributes.value': ?1}
    

    【讨论】:

    • 我尝试这样做,但更改项目中的所有内容太复杂了。我在第一条消息中的解决方案。
    猜你喜欢
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    相关资源
    最近更新 更多