Вопрос

I have a mongodb collection with multiple documents of following structure

{
    "_id" : "...",
    "_class" : "...",
    ...
    "travelers" : [
        {
            "id": "12345",
            "type": "XYZ"
        },
        {
            "id": "67890",
            "type": "ABC"
        }],
    ...
}

Using spring data, I am able to fetch documents that have traveler type XYZ :

Query query = new Query(Criteria.where("travelers.type").is("XYZ");
List<Something> something = mongoTemplate.find(query, Something.class, COLLECTION_NAME);

But if I switch the query to fetch by traveler id, I get no results:

Query query = new Query(Criteria.where("travelers.id").is("12345");
List<Something> something = mongoTemplate.find(query, Something.class, COLLECTION_NAME);

I enabled all logs and the outgoing query is {"travelers.id" : "12345"} which looks right. Running the query {"travelers.id" : "12345"} directly on the db returns the right results.

Other queries I have tried on the collection seem to work fine. I have tried both with & without index on travelers.id and no results in both cases. What am I doing wrong?

Это было полезно?

Решение

Fields with "id" name get special treatment in mapping - see http://docs.spring.io/spring-data/data-mongodb/docs/current/reference/html/#mongo-template.id-handling

What happens is that spring data mapping translates id to "_id" for your query when you do:

Query query = new Query(Criteria.where("travelers.id").is("12345");

so the query going to mongo isn't

{"travelers.id" : "12345"}

but is

{"travelers._id" : "12345"}

The queries logged by spring data mongo are little bit different to what actually goes to mongo.

Strange thing is that spring data doesn't do this mapping when saving the data.

Rename the id field to something like travelerId will solves the issue.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top