Simple joint query

62 views
Skip to first unread message

Razvan Bunea

unread,
Sep 16, 2021, 6:09:35 PM9/16/21
to kmongo
Hi,
Been playing around with trying to write a simple joint typed query between 2 collection but for the hell of me couldn't figure out form the documentation or the AggregateTest 

I have these 2 collections objects

data class UserDb(@BsonId val login: String, val password: String)
data class EmailDb(@BsonId val login: String, val email: String)


And I want to have in return

data class UserWithEmail(val login: String, val password: String, val email: String?)

I came this far: 

aggregate<UserWithEmail>(
        lookup(
            from = "emails",
            localField = UserDb::login.name,
            foreignField = EmailDb::login.name,
            newAs = UserWithEmail::email.name
        ),
        UserWithEmail::email.unwind(),
        project(
            UserWithEmail::login to UserDb::login,
            UserWithEmail::password to UserDb::password,
            UserWithEmail::email to "?"
        )
    )

But don't know what to put instead if "?"  and each entry is repeted twice

I tried to write the lookup with a variables, result, pipeline as in your Test exemple but didn't manage to make it work at all. 

Thanks in advance.

zigzago

unread,
Oct 18, 2021, 4:28:51 PM10/18/21
to kmongo
Hi,

This code should work:

aggregate<UserWithEmail>(
        lookup(
            from = "emails",
            localField = UserDb::login.name,
            foreignField = EmailDb::login.name,
            newAs = UserWithEmail::email.name
        ),
        UserWithEmail::email.unwind(),
        project(
            UserWithEmail::login from UserDb::login,
            UserWithEmail::password from UserDb::password,
            UserWithEmail::email from UserWithEmail::email
        )
    )

HTH
Reply all
Reply to author
Forward
0 new messages