MongoDb Spring find in nested object

你。 提交于 2021-01-28 02:00:59

问题


I'm using Spring Data Mongodb and documents like this :

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

I would like to query my collection to search a value in the attributes object (in the values and not the keys).

For example like this :

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

But I'm not sure to be able to do that. Any idea to help me ?

Best regards

edit: my solution

Well, what I've done is simple. I know every id (key in attributes fields) for that listId so I create a custom mongo opération

    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));

With some pagination.. And it works


回答1:


I think that you have to change the structure of attributes :

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

Then change you request like this :

{'attributes.value': ?1}


来源:https://stackoverflow.com/questions/34016419/mongodb-spring-find-in-nested-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!