Nested Document Fields
When accessing nested document fields, it is not possible to obtain them directly through lambda expressions. Therefore, MongoPlus provides alternative ways to build nested document fields, avoiding the need to write them as plain strings.
Nested document fields, also known as embedded documents, are for cases like when theUser
class has arole
property of typeRole
, and you want the value"role.roleName"
. This can be achieved using this approach.
FieldChain
- This class allows you to build nested document fields, making it more convenient than
FunctionUtil
. - You can also retrieve field names prefixed with
$
.
Example
Get nested fields
java
public class User {
private Role role;
}
public class Role {
private String roleName;
}
public static void main(String[] args) {
FieldChain fieldChain = FieldChain.of(User::getRole).then(Role::getUserName);
// Build the field name using build()
String fieldName = fieldChain.build();
// Output: role.roleName
System.out.println(fieldName);
// -------------------------------------------------------------------
// Build field name with $
String fieldNameOption = fieldChain.build(true);
// Output: $role.roleName
System.out.println(fieldNameOption);
}
FunctionUtil
- This class can also be used to build nested document fields.
- It is not limited to nested fields — it can also handle normal top-level fields.
- You can also retrieve field names prefixed with
$
.
Example
Get top-level fields
java
public class User {
private String userName;
}
public static void main(String[] args) {
// Get the field name. If @CollectionField annotation specifies a field name, that value will be returned.
String fieldName = FunctionUtil.getFieldName(User::getUserName)
// Output: userName
System.out.println(fieldName);
// -------------------------------------------------------------------
// Get the field name prefixed with $
String fieldName = FunctionUtil.getFieldNameOption(User::getUserName)
// Output: $userName
System.out.println(fieldName);
}
Get nested fields
java
public class User {
private Role role;
}
public class Role {
private String roleName;
}
public static void main(String[] args) {
// Build a nested document object
FunctionBuilder builder = FunctionUtil.builderFunction();
// Add fields to the FunctionBuilder object
builder.add(User::getRole).add(Role::getRoleName);
// Build the field name
String fieldName = builder.build();
// Output: role.roleName
System.out.println(fieldName);
// -------------------------------------------------------------------
// Build field name with $
String fieldNameOption = builder.build(true);
// Output: $role.roleName
System.out.println(fieldNameOption);
}