正如主题所说,我在Predicate
字段上涉及Map<String, String>
的查询时遇到问题。
我有以下测试用例重现问题:
@Test
public void testReferencesPredicate() throws Exception {
//cleans the event collection
final DBCollection event = mongoTemplate.getCollection("event");
event.drop();
final Event anEvent = new Event();
//event has some more fields
final Map<String, String> someRefs = new HashMap<>();
someRefs.put("a", "b");
anEvent.setReferences(someRefs);
final Event save = this.eventRepository.save(anEvent);
assertNotNull(save);
final BooleanBuilder refPredicate = new BooleanBuilder();
final Map<String, String> references = new HashMap<>();
references.put("a", "b");
for (final Map.Entry<String, String> stringObjectEntry : references.entrySet()) {
final String key = stringObjectEntry.getKey();
final String value = stringObjectEntry.getValue();
// this also doesn't work: refPredicate.and(QEvent.event.references.contains(key, value));
refPredicate.and(QEvent.event.references.get(key).eq(value));
}
final Pageable firstPage = new PageRequest(1, 1);
final Page<Event> all = this.eventRepository.findAll(refPredicate, firstPage);
assertNotNull(all);
assertEquals(1, all.getContent().size());
//the eventRepository is like this: public interface EventRepository extends MongoRepository<Event, ObjectId>,
QueryDslPredicateExecutor<Event>,
}
当mongo登录stdout客户端正在执行的查询时,我看到以下内容:
2015-07-30T10:49:24.399+0200 I QUERY [conn3] query some-db.event query: { references.a: "b" } planSummary: COLLSCAN ntoreturn:0 ntoskip:0 nscanned:0 nscannedObjects:1 keyUpdates:0 writeConflicts:0 numYields:0 nreturned:1 reslen:207 locks:{ Global: { acquireCount: { r: 2 } }, MMAPV1Journal: { acquireCount: { r: 1 } }, Database: { acquireCount: { r: 1 } }, Collection: { acquireCount: { R: 1 } } } 0ms
执行的查询似乎与mongo客户端的查询不同:
e = db.getCollection("event")
e.find({ "references.a": "b" })
请注意references.a
周围的引号,我认为这些引号用于访问嵌套的json文档。
有人经历过这个吗?
我在mongodb v3.0.4上的spring-data-mongodb-1.7.0.RELEASE