Search code examples
mongodbupsertjongomongo-collection

How to do upsert using jongo?


I have a users table/collection and would like to upsert a user - update a user if exists or add a new one if still not exists. Structure below.

By "exists", I mean having some external ID. In this case, googleId.

How can I do it using Jongo library? Thanks.

public class User {
    public String _id;
    public String email;
    public String givenName;
    public String familyName;
    public String googleId;
}

Solution

  • Considering having a user with an already loaded googleId (passed google auth), and I'd like to upsert it to mongoDB, using Jongo:

    // Init
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    DB db = mongoClient.getDB(DB_NAME);
    Jongo jongo = new Jongo(db);
    org.jongo.MongoCollection collectionJongo = jongo.getCollection(USER_COLLECTION_NAME);
    
    // Upsert
    String query = "{googleId: {$eq: #}}";
    collectionJongo.update(query, user.googleId)
            .upsert()
            .with(user);
    user = collectionJongo.find(query, user.googleId).as(User.class).next();
    // Works only on insert. On update, the upsertedId is null.
    //user._id = ((ObjectId) writeResult.getUpsertedId()).toHexString();