我需要根据MongoDB和中文档中某个字段的存在来投影一个布尔值。
让我们假设我的Mongo DB中有文档。它们的结构如下(testedField可能不存在):
{
"_id": ObjectId("some object ID"),
"field1": "some value",
"field2": "another value",
"testedField": "this field may be absent"
}
或者像这样:
{
"_id": ObjectId("some object ID"),
"field1": "some value",
"field2": "another value"
}
我还有一个数据类MyClass:
@AllArgsConstructor
@Getter
public class MyClass {
private String field1;
private String field2;
private boolean myBoolVal;
}
在我的DAO中,有一个方法将其字段的值投影到类中:
public List<MyClass> findThings(Collection<ObjectId> ids) {
Criteria criteria = where(ID).in(ids);
Aggregation matchAndProject = newAggregation(
match(criteria),
project("field1", "field2")
.and("testedField").ne(null).as("myBoolVal"));
return mongoTemplate.aggregate(matchAndProject, "my_collection", MyClass.class).getMappedResults();
}
如果存在true
myBoolVal字段,则使用testedField,如果不存在,则使用false
。
但是上面的代码抛出了IllegalArgumentException("Values must not be null!")
。
有办法让它起作用吗?
发布于 2019-12-25 14:15:34
我找到了解决方案:只使用when("fieldName")
而没有exists()
或is(null)
等就足够了。
public List<MyClass> findThings(Collection<ObjectId> ids) {
Criteria criteria = where(ID).in(ids);
Aggregation matchAndProject = newAggregation(
match(criteria),
project("field1", "field2")
.and(ConditionalOperators.when("testedField")
.then(true)
.otherwise(false))
.as("myBoolVal"));
return mongoTemplate.aggregate(matchAndProject, "my_collection", MyClass.class).getMappedResults();
}
发布于 2019-12-24 10:16:50
使用条件投影使用标准
public List<MyClass> findThings(Collection<ObjectId> ids) {
Cond condition = ConditionalOperators.when(Criteria.where("testedField")
.exists(true))
.then(true)
.otherwise(false)
;
Criteria criteria = where(ID).in(ids);
Aggregation matchAndProject = newAggregation(
match(criteria),
project("field1", "field2")
and(condition).as("myBoolVal"));
return mongoTemplate.aggregate(matchAndProject, "my_collection", MyClass.class).getMappedResults();
}
发布于 2019-12-24 08:59:26
为什么不使用Boolean
?true
(如果存在字段),false
和null
(如果不存在)。
但是在您的例子中,字段myBoolVal
anything等于false
。有一件事-你的字段是最终的,你不能用它们做任何操作.将实体字段设置为final
是不正确的。
最后一件事:你用Spring吗?它有一个用于使用mongodb的完美库,与mongodb的工作非常类似于jpa功能。
https://stackoverflow.com/questions/59466114
复制相似问题