I need to save two collections in my MongoDB using Java. Where one collection is Department and other collection is Employee. Where one Departm
If $id didn't work try just id like this
"employees" : [ { "$ref" : "employee", "id" : 1 }, { "$ref" : "employee", "id" : 2 } ]
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.