Avatar
0
Tran Duy Tung Beginner
Tran Duy Tung Beginner
Convert từ String sang objectId MongoDB
Em chào anh.
Em đang dùng Lookup trong MongoTemplate để join 2 collection như sau:
public List<UserWithDepartment> findUsersWithDepartments() {
ProjectionOperation projectionOperation = Aggregation.project()
.and(ConvertOperators.valueOf("userId").convertToObjectId()).as("userId");
Aggregation aggregation = Aggregation.newAggregation(
projectionOperation,
Aggregation.lookup(departmentCollectionName, "_id","userId","departments")
);
AggregationResults<UserWithDepartment> results = mongoTemplate.aggregate(
aggregation, userCollectionName, UserWithDepartment.class);
return results.getMappedResults();
}
Vấn đề của em là "_id" kiểu dữ liệu objectId còn "userId" kiểu dữ liệu String vì vậy em cần convert về 1 kiểu dữ liệu nhưng đang gặp lỗi này: Unrecognized expression '$toObjectId'
Anh đã gặp lỗi này chưa và cách khắc phục là gì ạ.
Em cảm ơn ạ
  • Answer
Remain: 5
1 Answer
Avatar
tvd12 Enlightened
tvd12 Enlightened
The Best Answer
Anh chưa gặp lỗi này bao giờ, cách khắc phục là em phải chuyển userId về ObjectId hoặc BsonObjectId, ví dụ:
if (value instanceof String) {
    return new ObjectId((String) value);
}
if (value instanceof BsonObjectId) {
    return ((BsonObjectId) value).getValue();
}
return (ObjectId) value;
Tham khảo: ezydata-mongodb.
  • 0
  • Reply