MongoDB按样例查询findOne

3

有些其他的进程向Mongo集合中插入文档,以下是示例数据:

{ "_id" : ObjectId("597b89c8da52380b04ee6948"), "_class" : "com.test.mongo", "clientId" : "CAQ123999", "isValid" : false, "isParent" : true }
{ "_id" : ObjectId("597b89c8da52380b04ee6949"), "_class" : "com.test.mongo", "clientId" : "CAQ123999", "isValid" : false, "isParent" : true }
{ "_id" : ObjectId("597b89c8da52380b04ee6950"), "_class" : "com.test.mongo", "clientId" : "CAQ123998", "isValid" : true, "isParent" : true }
{ "_id" : ObjectId("597b89c8da52380b04ee6951"), "_class" : "com.test.mongo", "clientId" : "CAQ123997", "isValid" : true, "isParent" : false }

我将尝试使用QueryByExampleExecutor获取一个客户端ID的记录。以下是我的模型:
package com.test.cfp.model;
public class TFSModel {

    private String clientId;
    private boolean isValid;
    private boolean isParent;
    ...

}

以下是构建示例的代码:

TFSModel tfs = new TFSModel();
            tfs.setClientId(CAQ123999);
            tfs.setValid(false);
            tfs.setParent(true);    
            ExampleMatcher matcher =ExampleMatcher.matching().withIgnoreNullValues().withIgnorePaths("_id","_class");
            Example<TFSModel > example = Example.of(tfs,matcher);           
            TFSModel oneTfsRecord  = tflsRepository.findOne(example);

这个不起作用了,以下是生成的查询

findOne using query: { "isValid" : false , "isParent" : true , "clientId" : "CAQ123999" , "_class" : { "$in" : [ "com.test.cfp.model.TFSModel"]}} in db.collection: returns.tfs;

显然,_class与mongo集合中的_class不同。我该如何告诉mongo在构建查询时不使用_class?我尝试过使用IgnoredPaths,但它没有起作用。

1个回答

1

MongoExampleMapper检查探针类型,并根据MappingContext中已知的类型编写类型限制。可分配给探针的类型包含在$in运算符中。

class One {
    @Id String id;
    String value;
    // ... 
}

class Two extends One {
    // ...
}

One probe = new One();
probe.value = "firefight";

Example<One> example = Example.of(probe, ExampleMatcher.matchingAny());

{
    value: firefight,
    _class: { $in : [ "com.example.One" , "com.example.Two" ] }
}

这种行为无法通过使用.withIgnorePaths()进行更改,因为_class指定符不是域模型的一部分。如果您认为应该考虑此问题,请在jira.spring.io上提交问题。

查看您提供的mongo集合示例数据时,_class属性与您的域类型不匹配,因此无法加载。


感谢@Christoph Strobl。我最终使用了MongoTemplate。我不确定这是否是有效的方案。无论如何,我会尝试在jira.spring.io中记录这个问题。 - PKR

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接