Collections
OneToMany
and ManyToMany
collections are stored in a Collection
wrapper. It implements
iterator so you can use for of
loop to iterate through it.
Another way to access collection items is to use bracket syntax like when you access array items.
Keep in mind that this approach will not check if the collection is initialed, while using get
method will throw error in this case.
Note that array access in
Collection
is available only for reading already loaded items, you cannot add new items toCollection
this way.
#
OneToMany collectionsOneToMany
collections are inverse side of ManyToOne
references, to which they need to point via fk
attribute:
#
ManyToMany collectionsAs opposed to SQL databases, with MongoDB we do not need to have join tables for ManyToMany
relations.
All references are stored as an array of ObjectID
s on owning entity.
#
UnidirectionalUnidirectional ManyToMany
relations are defined only on one side, and marked explicitly as owner
:
#
BidirectionalBidirectional ManyToMany
relations are defined on both sides, while one is owning side (where references are store),
marked by inversedBy
attribute pointing to the inverse side:
And on the inversed side we define it with mappedBy
attribute poining back to the owner:
#
Propagation of Collection's add() and remove() operationsWhen you use one of Collection.add()
method, the item is added to given collection,
and this action is also propagated to its counterpart.
For M:N this works in both ways, either from owning side, or from inverse side.
Collections on both sides have to be initialized, otherwise propagation won't work.
Although this propagation works also for M:N inverse side, you should always use owning side to manipulate the collection.
Same applies for Collection.remove()
.