A bullet of mass $m$ hits a sandbag of mass $M$ that is suspended from the ceiling by a massless rope. At the moment the bullet hits it has a horizontal velocity $v$, and it gets stuck in the sandbag. Find the maximum height the sandbag will rise during its swing. (Assume that the bullets comes to a stop immediately, acceleration due to gravity is $g=10m/s^2$, $m=10g$, $M=1kg$, $v=100m/s^2$.)
I have been taught that momentum is always conserved in any type of collision and energy is only conserved during elastic collisions, but it does not seem to be the case here.
The proposed solution was broken down into two parts. The first part regards the collision itself, i.e momentum is conserved. It follows then that the final velocity is given by $$v'=\frac{mv}{(M+m)}$$ The second part concerns about the moment the bullet got into the sandbag which is an inelastic collision, thus "energy is conserved but momentum is not." It follows then that the maximum height is given by $$h=\frac{m^2v^2}{2g(M+m)^2}$$
It is unclear to me why energy is conserved (and momentum is not) in this specific collision since both the bullet and the sandbag stick together. What am I missing here?