I have Office object:
class Office{
String address;
int employees;
String city;
String State;
---- lot of other fields
}
I have mongo
collections for Office class that have lets say 100 Office documents represented by above Office class.
Then I have Employee class:
class Employee{
String firstName;
String lastName;
Office office;
-----other fields
}
In mongo collection for Employee class how I can prevent Office object to be copied for each Employee entry.
In spring-boot mongodb
is there way I can refer to Office collection to represent Office object of Employee instead of copying it for each employee in mongo db. I hope I have explained my problem.
Thanks in advance.
For performing MongoDB Join two collections, you must use the $lookup operator. It is defined as a stage that executes a left outer join with another collection and aids in filtering data from joined documents. For example, if a user requires all grades from all students, then the below query can be written: Students.
In MongoDB, we can combine data of multiple collections into one through the $lookup aggregation stage. In this, you have to specify which collection you want to join with the current collection and select the field that matches in both the collection.
With the help of mongoose, we will move a MongoDB document from one collection to another. Make sure that in the schema of both the collections all the fields are the same. Install mongoose: Step 1: You can visit the link Install mongoose to install the mongoose module.
The @Id annotation tells the mapper which property you want to use for the MongoDB _id property and the @Indexed annotation tells the mapping framework to call ensureIndex on that property of your document, making searches faster.
You can use the DBRef in Mongo. Spring Data brings an annotation for that:
@DBRef
But, be careful, MongoDB is a document-oriented NoSQL and is a good practice to embed stuff inside a document. This approach can lead you to a bigger problem.
Edit:
Use the @DBRef
like this:
https://docs.spring.io/spring-data/data-mongo/docs/1.7.0.RELEASE/reference/html/#mapping-usage-references
Here is the code which you can use:
@Document(collection="person")
public class Person
{
@Id
private Long personId;
private String name;
private int age;
@DBRef(db="address")
private List<Address> addresses = new ArrayList<Address>();
//other getters and setters
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With