One way to do it is via line plane intersection, as seen here:
Essentially, think of it as a virtual plane which you place wherever you want, and then trace from the camera’s location towards the mouse cursor. You hit the plane at the intersection point.
Super useful if there is no geometry, you do not wish to rely on it, you’d rather ignore it or it’s a projection of sort - think VR interface.
Another way is to use collision channels where you decide what the trace works against (visibility by default - hence you’re hitting everything you see). You may only wish to trace against undulating terrain but not the trees, rocks, obstacles and so on.
In which case, you’d assign a dedicated channel to detecting where the mouse cursor is in relation to the ground. Depending on what the end goal is, it might be a preferable and less ham-fisted approach than the above-mentioned line trace intersection.