Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb with Java foreign key

I need to save two collections in my MongoDB using Java. Where one collection is Department and other collection is Employee. Where one Department can have many employees I want to save a collection like an employee unique ID has to mapped in my department employee list.

Example:

{
    "_id" : ObjectId("598da19250aa4ad2413d4bc0"),
    "_class" : "com.department",
    "departmentName" : "SAQ-A",
    "departmentNumber" : "3_2",
    "employee" : [ 
           "id" : "1",
           "id" : "2",
           "id" : "3"
     ]
}

Can I know what is the way I can achieve it in MongoDB using Java?

like image 379
suresh Avatar asked Jan 19 '26 18:01

suresh


1 Answers

By the provided document and tags I assume you are using spring data to deal with mongodb. So here you may want to use DBRefs to bind employees into departments. Luckily Spring Data gives you @DBRef annotation.

Employee class:

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document
public class Employee {

    @Id
    private Integer id;
    ...

}

Department class:

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;

@Document
public class Department {

    @Id
    private String id;

    @DBRef
    private Collection<Employee> employees;
    ...
}

MongoDB document:

{
    "_id" : ObjectId("598dc04ac4fdd0e29867ccbb"),
    "_class" : "foo.bar.Department",
    "employees" : [ 
        {
            "$ref" : "employee",
            "$id" : 1
        }, 
        {
            "$ref" : "employee",
            "$id" : 2
        }
    ]
}

Note: Employee instance must already exist in MongoDB. DBRef will not save Employees in cascade style. Look at this article about cascading.

like image 135
mmadruga Avatar answered Jan 22 '26 10:01

mmadruga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!