Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb Spring find in nested object

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

like image 628
BkSouX Avatar asked May 29 '26 16:05

BkSouX


1 Answers

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}
like image 61
Oussama Zoghlami Avatar answered Jun 01 '26 06:06

Oussama Zoghlami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!